blame: move blame_entry duplication to add_blame_entry()
[git/git.git] / builtin / blame.c
CommitLineData
cee7f245 1/*
31653c1a 2 * Blame
cee7f245 3 *
7e6ac6e4
DK
4 * Copyright (c) 2006, 2014 by its authors
5 * See COPYING for licensing conditions
cee7f245
JH
6 */
7
8#include "cache.h"
fb58c8d5 9#include "refs.h"
cee7f245
JH
10#include "builtin.h"
11#include "blob.h"
12#include "commit.h"
13#include "tag.h"
14#include "tree-walk.h"
15#include "diff.h"
16#include "diffcore.h"
17#include "revision.h"
717d1462 18#include "quote.h"
cee7f245 19#include "xdiff-interface.h"
1cfe7733 20#include "cache-tree.h"
c455c87c 21#include "string-list.h"
f9567384 22#include "mailmap.h"
7e6ac6e4 23#include "mergesort.h"
5817da01 24#include "parse-options.h"
7e6ac6e4 25#include "prio-queue.h"
ffaf9cc0 26#include "utf8.h"
3b8a12e8 27#include "userdiff.h"
25ed3412 28#include "line-range.h"
58dbfa2e 29#include "line-log.h"
dbe44faa 30#include "dir.h"
aba37f49 31#include "progress.h"
cee7f245 32
ce41720c 33static char blame_usage[] = N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>");
5817da01
PH
34
35static const char *blame_opt_usage[] = {
36 blame_usage,
37 "",
9c9b4f2f 38 N_("<rev-opts> are documented in git-rev-list(1)"),
5817da01
PH
39 NULL
40};
cee7f245
JH
41
42static int longest_file;
43static int longest_author;
44static int max_orig_digits;
45static int max_digits;
5ff62c30 46static int max_score_digits;
4c10a5ca 47static int show_root;
85af7929 48static int reverse;
4c10a5ca 49static int blank_boundary;
717d1462 50static int incremental;
582aa00b 51static int xdl_opts;
84393bfd 52static int abbrev = -1;
3d1aa566 53static int no_whole_file_rename;
aba37f49 54static int show_progress;
31653c1a 55
a5481a6c 56static struct date_mode blame_date_mode = { DATE_ISO8601 };
31653c1a
EL
57static size_t blame_date_width;
58
2721ce21 59static struct string_list mailmap = STRING_LIST_INIT_NODUP;
cee7f245 60
54a4c617
JH
61#ifndef DEBUG
62#define DEBUG 0
63#endif
64
c2e525d9
JH
65/* stats */
66static int num_read_blob;
67static int num_get_patch;
68static int num_commits;
69
d24bba80 70#define PICKAXE_BLAME_MOVE 01
18abd745
JH
71#define PICKAXE_BLAME_COPY 02
72#define PICKAXE_BLAME_COPY_HARDER 04
c63777c0 73#define PICKAXE_BLAME_COPY_HARDEST 010
d24bba80 74
4a0fc95f
JH
75/*
76 * blame for a blame_entry with score lower than these thresholds
77 * is not passed to the parent using move/copy logic.
78 */
79static unsigned blame_move_score;
80static unsigned blame_copy_score;
81#define BLAME_DEFAULT_MOVE_SCORE 20
82#define BLAME_DEFAULT_COPY_SCORE 40
83
208acbfb 84/* Remember to update object flag allocation in object.h */
cee7f245
JH
85#define METAINFO_SHOWN (1u<<12)
86#define MORE_THAN_ONE_PATH (1u<<13)
87
88/*
54a4c617 89 * One blob in a commit that is being suspected
cee7f245
JH
90 */
91struct origin {
54a4c617 92 int refcnt;
7e6ac6e4 93 /* Record preceding blame record for this blob */
96e11709 94 struct origin *previous;
7e6ac6e4
DK
95 /* origins are put in a list linked via `next' hanging off the
96 * corresponding commit's util field in order to make finding
97 * them fast. The presence in this chain does not count
98 * towards the origin's reference count. It is tempting to
99 * let it count as long as the commit is pending examination,
100 * but even under circumstances where the commit will be
101 * present multiple times in the priority queue of unexamined
102 * commits, processing the first instance will not leave any
103 * work requiring the origin data for the second instance. An
104 * interspersed commit changing that would have to be
105 * preexisting with a different ancestry and with the same
106 * commit date in order to wedge itself between two instances
107 * of the same commit in the priority queue _and_ produce
108 * blame entries relevant for it. While we don't want to let
109 * us get tripped up by this case, it certainly does not seem
110 * worth optimizing for.
111 */
112 struct origin *next;
cee7f245 113 struct commit *commit;
7e6ac6e4
DK
114 /* `suspects' contains blame entries that may be attributed to
115 * this origin's commit or to parent commits. When a commit
116 * is being processed, all suspects will be moved, either by
117 * assigning them to an origin in a different commit, or by
118 * shipping them to the scoreboard's ent list because they
119 * cannot be attributed to a different commit.
120 */
121 struct blame_entry *suspects;
c2e525d9 122 mmfile_t file;
cee7f245 123 unsigned char blob_sha1[20];
90064710 124 unsigned mode;
7e6ac6e4
DK
125 /* guilty gets set when shipping any suspects to the final
126 * blame list instead of other commits
127 */
128 char guilty;
cee7f245
JH
129 char path[FLEX_ARRAY];
130};
131
aba37f49
ECA
132struct progress_info {
133 struct progress *progress;
134 int blamed_lines;
135};
136
17a07e2a 137static int diff_hunks(mmfile_t *file_a, mmfile_t *file_b,
4b4132fd
RS
138 xdl_emit_hunk_consume_func_t hunk_func, void *cb_data)
139{
140 xpparam_t xpp = {0};
141 xdemitconf_t xecfg = {0};
85c20c30 142 xdemitcb_t ecb = {NULL};
4b4132fd
RS
143
144 xpp.flags = xdl_opts;
4b4132fd
RS
145 xecfg.hunk_func = hunk_func;
146 ecb.priv = cb_data;
147 return xdi_diff(file_a, file_b, &xpp, &xecfg, &ecb);
148}
149
3b8a12e8
AB
150/*
151 * Prepare diff_filespec and convert it using diff textconv API
152 * if the textconv driver exists.
153 * Return 1 if the conversion succeeds, 0 otherwise.
154 */
e5fba602 155int textconv_object(const char *path,
90064710 156 unsigned mode,
e5fba602 157 const unsigned char *sha1,
e5450100 158 int sha1_valid,
e5fba602
CP
159 char **buf,
160 unsigned long *buf_size)
3b8a12e8
AB
161{
162 struct diff_filespec *df;
163 struct userdiff_driver *textconv;
164
165 df = alloc_filespec(path);
e5450100 166 fill_filespec(df, sha1, sha1_valid, mode);
3b8a12e8
AB
167 textconv = get_textconv(df);
168 if (!textconv) {
169 free_filespec(df);
170 return 0;
171 }
172
173 *buf_size = fill_textconv(textconv, df, buf);
174 free_filespec(df);
175 return 1;
176}
177
1732a1fd
JH
178/*
179 * Given an origin, prepare mmfile_t structure to be used by the
180 * diff machinery
181 */
3b8a12e8
AB
182static void fill_origin_blob(struct diff_options *opt,
183 struct origin *o, mmfile_t *file)
c2e525d9
JH
184{
185 if (!o->file.ptr) {
21666f1a 186 enum object_type type;
3b8a12e8
AB
187 unsigned long file_size;
188
c2e525d9 189 num_read_blob++;
3b8a12e8 190 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&
e5450100 191 textconv_object(o->path, o->mode, o->blob_sha1, 1, &file->ptr, &file_size))
3b8a12e8
AB
192 ;
193 else
194 file->ptr = read_sha1_file(o->blob_sha1, &type, &file_size);
195 file->size = file_size;
196
ab43e495
JH
197 if (!file->ptr)
198 die("Cannot read blob %s for path %s",
199 sha1_to_hex(o->blob_sha1),
200 o->path);
c2e525d9
JH
201 o->file = *file;
202 }
203 else
204 *file = o->file;
c2e525d9
JH
205}
206
1732a1fd
JH
207/*
208 * Origin is refcounted and usually we keep the blob contents to be
209 * reused.
210 */
54a4c617
JH
211static inline struct origin *origin_incref(struct origin *o)
212{
213 if (o)
214 o->refcnt++;
215 return o;
216}
217
218static void origin_decref(struct origin *o)
219{
220 if (o && --o->refcnt <= 0) {
7e6ac6e4 221 struct origin *p, *l = NULL;
96e11709
JH
222 if (o->previous)
223 origin_decref(o->previous);
8e0f7003 224 free(o->file.ptr);
7e6ac6e4
DK
225 /* Should be present exactly once in commit chain */
226 for (p = o->commit->util; p; l = p, p = p->next) {
227 if (p == o) {
228 if (l)
229 l->next = p->next;
230 else
231 o->commit->util = p->next;
232 free(o);
233 return;
234 }
235 }
236 die("internal error in blame::origin_decref");
54a4c617
JH
237 }
238}
239
7c3c7962
JH
240static void drop_origin_blob(struct origin *o)
241{
242 if (o->file.ptr) {
243 free(o->file.ptr);
244 o->file.ptr = NULL;
245 }
246}
247
1732a1fd
JH
248/*
249 * Each group of lines is described by a blame_entry; it can be split
7e6ac6e4
DK
250 * as we pass blame to the parents. They are arranged in linked lists
251 * kept as `suspects' of some unprocessed origin, or entered (when the
252 * blame origin has been finalized) into the scoreboard structure.
253 * While the scoreboard structure is only sorted at the end of
254 * processing (according to final image line number), the lists
255 * attached to an origin are sorted by the target line number.
1732a1fd 256 */
cee7f245 257struct blame_entry {
cee7f245
JH
258 struct blame_entry *next;
259
260 /* the first line of this group in the final image;
261 * internally all line numbers are 0 based.
262 */
263 int lno;
264
265 /* how many lines this group has */
266 int num_lines;
267
268 /* the commit that introduced this group into the final image */
269 struct origin *suspect;
270
cee7f245
JH
271 /* the line number of the first line of this group in the
272 * suspect's file; internally all line numbers are 0 based.
273 */
274 int s_lno;
5ff62c30
JH
275
276 /* how significant this entry is -- cached to avoid
1732a1fd 277 * scanning the lines over and over.
5ff62c30
JH
278 */
279 unsigned score;
cee7f245
JH
280};
281
7e6ac6e4
DK
282/*
283 * Any merge of blames happens on lists of blames that arrived via
284 * different parents in a single suspect. In this case, we want to
285 * sort according to the suspect line numbers as opposed to the final
286 * image line numbers. The function body is somewhat longish because
287 * it avoids unnecessary writes.
288 */
289
290static struct blame_entry *blame_merge(struct blame_entry *list1,
291 struct blame_entry *list2)
292{
293 struct blame_entry *p1 = list1, *p2 = list2,
294 **tail = &list1;
295
296 if (!p1)
297 return p2;
298 if (!p2)
299 return p1;
300
301 if (p1->s_lno <= p2->s_lno) {
302 do {
303 tail = &p1->next;
304 if ((p1 = *tail) == NULL) {
305 *tail = p2;
306 return list1;
307 }
308 } while (p1->s_lno <= p2->s_lno);
309 }
310 for (;;) {
311 *tail = p2;
312 do {
313 tail = &p2->next;
314 if ((p2 = *tail) == NULL) {
315 *tail = p1;
316 return list1;
317 }
318 } while (p1->s_lno > p2->s_lno);
319 *tail = p1;
320 do {
321 tail = &p1->next;
322 if ((p1 = *tail) == NULL) {
323 *tail = p2;
324 return list1;
325 }
326 } while (p1->s_lno <= p2->s_lno);
327 }
328}
329
330static void *get_next_blame(const void *p)
331{
332 return ((struct blame_entry *)p)->next;
333}
334
335static void set_next_blame(void *p1, void *p2)
336{
337 ((struct blame_entry *)p1)->next = p2;
338}
339
340/*
341 * Final image line numbers are all different, so we don't need a
342 * three-way comparison here.
343 */
344
345static int compare_blame_final(const void *p1, const void *p2)
346{
347 return ((struct blame_entry *)p1)->lno > ((struct blame_entry *)p2)->lno
348 ? 1 : -1;
349}
350
351static int compare_blame_suspect(const void *p1, const void *p2)
352{
353 const struct blame_entry *s1 = p1, *s2 = p2;
354 /*
355 * to allow for collating suspects, we sort according to the
356 * respective pointer value as the primary sorting criterion.
357 * The actual relation is pretty unimportant as long as it
358 * establishes a total order. Comparing as integers gives us
359 * that.
360 */
361 if (s1->suspect != s2->suspect)
362 return (intptr_t)s1->suspect > (intptr_t)s2->suspect ? 1 : -1;
363 if (s1->s_lno == s2->s_lno)
364 return 0;
365 return s1->s_lno > s2->s_lno ? 1 : -1;
366}
367
368static struct blame_entry *blame_sort(struct blame_entry *head,
369 int (*compare_fn)(const void *, const void *))
370{
371 return llist_mergesort (head, get_next_blame, set_next_blame, compare_fn);
372}
373
374static int compare_commits_by_reverse_commit_date(const void *a,
375 const void *b,
376 void *c)
377{
378 return -compare_commits_by_commit_date(a, b, c);
379}
380
1732a1fd
JH
381/*
382 * The current state of the blame assignment.
383 */
cee7f245
JH
384struct scoreboard {
385 /* the final commit (i.e. where we started digging from) */
386 struct commit *final;
7e6ac6e4
DK
387 /* Priority queue for commits with unassigned blame records */
388 struct prio_queue commits;
85af7929 389 struct rev_info *revs;
cee7f245
JH
390 const char *path;
391
1732a1fd
JH
392 /*
393 * The contents in the final image.
394 * Used by many functions to obtain contents of the nth line,
395 * indexed with scoreboard.lineno[blame_entry.lno].
cee7f245
JH
396 */
397 const char *final_buf;
398 unsigned long final_buf_size;
399
400 /* linked list of blames */
401 struct blame_entry *ent;
402
612702e8 403 /* look-up a line in the final buffer */
cee7f245
JH
404 int num_lines;
405 int *lineno;
406};
407
54a4c617
JH
408static void sanity_check_refcnt(struct scoreboard *);
409
1732a1fd
JH
410/*
411 * If two blame entries that are next to each other came from
412 * contiguous lines in the same origin (i.e. <commit, path> pair),
413 * merge them together.
414 */
cee7f245
JH
415static void coalesce(struct scoreboard *sb)
416{
417 struct blame_entry *ent, *next;
418
419 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
0a88f08e 420 if (ent->suspect == next->suspect &&
cee7f245
JH
421 ent->s_lno + ent->num_lines == next->s_lno) {
422 ent->num_lines += next->num_lines;
423 ent->next = next->next;
54a4c617 424 origin_decref(next->suspect);
cee7f245 425 free(next);
46014766 426 ent->score = 0;
cee7f245
JH
427 next = ent; /* again */
428 }
429 }
54a4c617
JH
430
431 if (DEBUG) /* sanity */
432 sanity_check_refcnt(sb);
cee7f245
JH
433}
434
7e6ac6e4
DK
435/*
436 * Merge the given sorted list of blames into a preexisting origin.
437 * If there were no previous blames to that commit, it is entered into
438 * the commit priority queue of the score board.
439 */
440
441static void queue_blames(struct scoreboard *sb, struct origin *porigin,
442 struct blame_entry *sorted)
443{
444 if (porigin->suspects)
445 porigin->suspects = blame_merge(porigin->suspects, sorted);
446 else {
447 struct origin *o;
448 for (o = porigin->commit->util; o; o = o->next) {
449 if (o->suspects) {
450 porigin->suspects = sorted;
451 return;
452 }
453 }
454 porigin->suspects = sorted;
455 prio_queue_put(&sb->commits, porigin->commit);
456 }
457}
458
1732a1fd
JH
459/*
460 * Given a commit and a path in it, create a new origin structure.
461 * The callers that add blame to the scoreboard should use
462 * get_origin() to obtain shared, refcounted copy instead of calling
463 * this function directly.
464 */
854b97f6
JH
465static struct origin *make_origin(struct commit *commit, const char *path)
466{
467 struct origin *o;
96ffc06f 468 FLEX_ALLOC_STR(o, path, path);
854b97f6
JH
469 o->commit = commit;
470 o->refcnt = 1;
7e6ac6e4
DK
471 o->next = commit->util;
472 commit->util = o;
854b97f6
JH
473 return o;
474}
475
1732a1fd
JH
476/*
477 * Locate an existing origin or create a new one.
7e6ac6e4 478 * This moves the origin to front position in the commit util list.
1732a1fd 479 */
f6c0e191
JH
480static struct origin *get_origin(struct scoreboard *sb,
481 struct commit *commit,
482 const char *path)
cee7f245 483{
7e6ac6e4 484 struct origin *o, *l;
cee7f245 485
7e6ac6e4
DK
486 for (o = commit->util, l = NULL; o; l = o, o = o->next) {
487 if (!strcmp(o->path, path)) {
488 /* bump to front */
489 if (l) {
490 l->next = o->next;
491 o->next = commit->util;
492 commit->util = o;
493 }
494 return origin_incref(o);
495 }
cee7f245 496 }
854b97f6 497 return make_origin(commit, path);
cee7f245
JH
498}
499
1732a1fd
JH
500/*
501 * Fill the blob_sha1 field of an origin if it hasn't, so that later
502 * call to fill_origin_blob() can use it to locate the data. blob_sha1
503 * for an origin is also used to pass the blame for the entire file to
504 * the parent to detect the case where a child's blob is identical to
505 * that of its parent's.
90064710
KS
506 *
507 * This also fills origin->mode for corresponding tree path.
1732a1fd 508 */
90064710 509static int fill_blob_sha1_and_mode(struct origin *origin)
f6c0e191 510{
f6c0e191
JH
511 if (!is_null_sha1(origin->blob_sha1))
512 return 0;
ed1c9977 513 if (get_tree_entry(origin->commit->object.oid.hash,
f6c0e191 514 origin->path,
90064710 515 origin->blob_sha1, &origin->mode))
f6c0e191 516 goto error_out;
21666f1a 517 if (sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB)
f6c0e191
JH
518 goto error_out;
519 return 0;
520 error_out:
521 hashclr(origin->blob_sha1);
90064710 522 origin->mode = S_IFINVALID;
f6c0e191
JH
523 return -1;
524}
525
1732a1fd
JH
526/*
527 * We have an origin -- check if the same path exists in the
528 * parent and return an origin structure to represent it.
529 */
f6c0e191 530static struct origin *find_origin(struct scoreboard *sb,
cee7f245
JH
531 struct commit *parent,
532 struct origin *origin)
533{
7e6ac6e4 534 struct origin *porigin;
cee7f245 535 struct diff_options diff_opts;
f6c0e191
JH
536 const char *paths[2];
537
7e6ac6e4
DK
538 /* First check any existing origins */
539 for (porigin = parent->util; porigin; porigin = porigin->next)
540 if (!strcmp(porigin->path, origin->path)) {
1732a1fd
JH
541 /*
542 * The same path between origin and its parent
543 * without renaming -- the most common case.
544 */
7e6ac6e4 545 return origin_incref (porigin);
854b97f6 546 }
0d981c67 547
f6c0e191
JH
548 /* See if the origin->path is different between parent
549 * and origin first. Most of the time they are the
550 * same and diff-tree is fairly efficient about this.
551 */
552 diff_setup(&diff_opts);
8f67f8ae 553 DIFF_OPT_SET(&diff_opts, RECURSIVE);
f6c0e191
JH
554 diff_opts.detect_rename = 0;
555 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
556 paths[0] = origin->path;
557 paths[1] = NULL;
558
4a2d5ae2
NTND
559 parse_pathspec(&diff_opts.pathspec,
560 PATHSPEC_ALL_MAGIC & ~PATHSPEC_LITERAL,
561 PATHSPEC_LITERAL_PATH, "", paths);
28452655 562 diff_setup_done(&diff_opts);
1cfe7733 563
f2fd0760 564 if (is_null_oid(&origin->commit->object.oid))
ed1c9977 565 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);
1cfe7733 566 else
ed1c9977 567 diff_tree_sha1(parent->tree->object.oid.hash,
568 origin->commit->tree->object.oid.hash,
1cfe7733 569 "", &diff_opts);
f6c0e191
JH
570 diffcore_std(&diff_opts);
571
f6c0e191
JH
572 if (!diff_queued_diff.nr) {
573 /* The path is the same as parent */
574 porigin = get_origin(sb, parent, origin->path);
575 hashcpy(porigin->blob_sha1, origin->blob_sha1);
90064710 576 porigin->mode = origin->mode;
a9b2d424
JH
577 } else {
578 /*
579 * Since origin->path is a pathspec, if the parent
580 * commit had it as a directory, we will see a whole
581 * bunch of deletion of files in the directory that we
582 * do not care about.
583 */
584 int i;
585 struct diff_filepair *p = NULL;
586 for (i = 0; i < diff_queued_diff.nr; i++) {
587 const char *name;
588 p = diff_queued_diff.queue[i];
589 name = p->one->path ? p->one->path : p->two->path;
590 if (!strcmp(name, origin->path))
591 break;
592 }
593 if (!p)
594 die("internal error in blame::find_origin");
f6c0e191
JH
595 switch (p->status) {
596 default:
acca687f 597 die("internal error in blame::find_origin (%c)",
f6c0e191
JH
598 p->status);
599 case 'M':
600 porigin = get_origin(sb, parent, origin->path);
a0d12c44 601 hashcpy(porigin->blob_sha1, p->one->oid.hash);
90064710 602 porigin->mode = p->one->mode;
f6c0e191
JH
603 break;
604 case 'A':
605 case 'T':
606 /* Did not exist in parent, or type changed */
607 break;
608 }
609 }
610 diff_flush(&diff_opts);
ed6e8038 611 clear_pathspec(&diff_opts.pathspec);
f69e743d
JH
612 return porigin;
613}
f6c0e191 614
1732a1fd
JH
615/*
616 * We have an origin -- find the path that corresponds to it in its
617 * parent and return an origin structure to represent it.
618 */
f69e743d
JH
619static struct origin *find_rename(struct scoreboard *sb,
620 struct commit *parent,
621 struct origin *origin)
622{
623 struct origin *porigin = NULL;
624 struct diff_options diff_opts;
625 int i;
cee7f245
JH
626
627 diff_setup(&diff_opts);
8f67f8ae 628 DIFF_OPT_SET(&diff_opts, RECURSIVE);
cee7f245
JH
629 diff_opts.detect_rename = DIFF_DETECT_RENAME;
630 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
2f3f8b21 631 diff_opts.single_follow = origin->path;
28452655 632 diff_setup_done(&diff_opts);
1cfe7733 633
f2fd0760 634 if (is_null_oid(&origin->commit->object.oid))
ed1c9977 635 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);
1cfe7733 636 else
ed1c9977 637 diff_tree_sha1(parent->tree->object.oid.hash,
638 origin->commit->tree->object.oid.hash,
1cfe7733 639 "", &diff_opts);
cee7f245
JH
640 diffcore_std(&diff_opts);
641
642 for (i = 0; i < diff_queued_diff.nr; i++) {
643 struct diff_filepair *p = diff_queued_diff.queue[i];
612702e8 644 if ((p->status == 'R' || p->status == 'C') &&
f6c0e191
JH
645 !strcmp(p->two->path, origin->path)) {
646 porigin = get_origin(sb, parent, p->one->path);
a0d12c44 647 hashcpy(porigin->blob_sha1, p->one->oid.hash);
90064710 648 porigin->mode = p->one->mode;
cee7f245
JH
649 break;
650 }
651 }
652 diff_flush(&diff_opts);
ed6e8038 653 clear_pathspec(&diff_opts.pathspec);
cee7f245
JH
654 return porigin;
655}
656
1732a1fd 657/*
7e6ac6e4 658 * Append a new blame entry to a given output queue.
1732a1fd 659 */
dfa3ad32
RS
660static void add_blame_entry(struct blame_entry ***queue,
661 const struct blame_entry *src)
cee7f245 662{
dfa3ad32
RS
663 struct blame_entry *e = xmalloc(sizeof(*e));
664 memcpy(e, src, sizeof(*e));
54a4c617
JH
665 origin_incref(e->suspect);
666
7e6ac6e4
DK
667 e->next = **queue;
668 **queue = e;
669 *queue = &e->next;
cee7f245
JH
670}
671
1732a1fd
JH
672/*
673 * src typically is on-stack; we want to copy the information in it to
7e6ac6e4
DK
674 * a malloced blame_entry that gets added to the given queue. The
675 * origin of dst loses a refcnt.
1732a1fd 676 */
7e6ac6e4
DK
677static void dup_entry(struct blame_entry ***queue,
678 struct blame_entry *dst, struct blame_entry *src)
cee7f245 679{
54a4c617
JH
680 origin_incref(src->suspect);
681 origin_decref(dst->suspect);
cee7f245 682 memcpy(dst, src, sizeof(*src));
7e6ac6e4
DK
683 dst->next = **queue;
684 **queue = dst;
685 *queue = &dst->next;
cee7f245
JH
686}
687
25ed3412 688static const char *nth_line(struct scoreboard *sb, long lno)
cee7f245
JH
689{
690 return sb->final_buf + sb->lineno[lno];
691}
692
25ed3412
BY
693static const char *nth_line_cb(void *data, long lno)
694{
695 return nth_line((struct scoreboard *)data, lno);
696}
697
1732a1fd
JH
698/*
699 * It is known that lines between tlno to same came from parent, and e
700 * has an overlap with that range. it also is known that parent's
701 * line plno corresponds to e's line tlno.
702 *
703 * <---- e ----->
704 * <------>
705 * <------------>
706 * <------------>
707 * <------------------>
708 *
709 * Split e into potentially three parts; before this chunk, the chunk
710 * to be blamed for the parent, and after that portion.
711 */
54a4c617 712static void split_overlap(struct blame_entry *split,
cee7f245
JH
713 struct blame_entry *e,
714 int tlno, int plno, int same,
715 struct origin *parent)
716{
cee7f245
JH
717 int chunk_end_lno;
718 memset(split, 0, sizeof(struct blame_entry [3]));
719
720 if (e->s_lno < tlno) {
721 /* there is a pre-chunk part not blamed on parent */
54a4c617 722 split[0].suspect = origin_incref(e->suspect);
cee7f245
JH
723 split[0].lno = e->lno;
724 split[0].s_lno = e->s_lno;
725 split[0].num_lines = tlno - e->s_lno;
726 split[1].lno = e->lno + tlno - e->s_lno;
727 split[1].s_lno = plno;
728 }
729 else {
730 split[1].lno = e->lno;
731 split[1].s_lno = plno + (e->s_lno - tlno);
732 }
733
734 if (same < e->s_lno + e->num_lines) {
735 /* there is a post-chunk part not blamed on parent */
54a4c617 736 split[2].suspect = origin_incref(e->suspect);
cee7f245
JH
737 split[2].lno = e->lno + (same - e->s_lno);
738 split[2].s_lno = e->s_lno + (same - e->s_lno);
739 split[2].num_lines = e->s_lno + e->num_lines - same;
740 chunk_end_lno = split[2].lno;
741 }
742 else
743 chunk_end_lno = e->lno + e->num_lines;
744 split[1].num_lines = chunk_end_lno - split[1].lno;
745
1732a1fd
JH
746 /*
747 * if it turns out there is nothing to blame the parent for,
748 * forget about the splitting. !split[1].suspect signals this.
749 */
cee7f245
JH
750 if (split[1].num_lines < 1)
751 return;
54a4c617 752 split[1].suspect = origin_incref(parent);
cee7f245
JH
753}
754
1732a1fd
JH
755/*
756 * split_overlap() divided an existing blame e into up to three parts
7e6ac6e4 757 * in split. Any assigned blame is moved to queue to
1732a1fd
JH
758 * reflect the split.
759 */
7e6ac6e4
DK
760static void split_blame(struct blame_entry ***blamed,
761 struct blame_entry ***unblamed,
54a4c617 762 struct blame_entry *split,
cee7f245
JH
763 struct blame_entry *e)
764{
cee7f245 765 if (split[0].suspect && split[2].suspect) {
1732a1fd 766 /* The first part (reuse storage for the existing entry e) */
7e6ac6e4 767 dup_entry(unblamed, e, &split[0]);
cee7f245 768
1732a1fd 769 /* The last part -- me */
dfa3ad32 770 add_blame_entry(unblamed, &split[2]);
cee7f245 771
1732a1fd 772 /* ... and the middle part -- parent */
dfa3ad32 773 add_blame_entry(blamed, &split[1]);
cee7f245
JH
774 }
775 else if (!split[0].suspect && !split[2].suspect)
1732a1fd
JH
776 /*
777 * The parent covers the entire area; reuse storage for
778 * e and replace it with the parent.
779 */
7e6ac6e4 780 dup_entry(blamed, e, &split[1]);
cee7f245 781 else if (split[0].suspect) {
1732a1fd 782 /* me and then parent */
7e6ac6e4 783 dup_entry(unblamed, e, &split[0]);
dfa3ad32 784 add_blame_entry(blamed, &split[1]);
cee7f245
JH
785 }
786 else {
1732a1fd 787 /* parent and then me */
7e6ac6e4 788 dup_entry(blamed, e, &split[1]);
dfa3ad32 789 add_blame_entry(unblamed, &split[2]);
cee7f245
JH
790 }
791}
792
1732a1fd
JH
793/*
794 * After splitting the blame, the origins used by the
795 * on-stack blame_entry should lose one refcnt each.
796 */
54a4c617
JH
797static void decref_split(struct blame_entry *split)
798{
799 int i;
800
801 for (i = 0; i < 3; i++)
802 origin_decref(split[i].suspect);
803}
804
1732a1fd 805/*
7e6ac6e4
DK
806 * reverse_blame reverses the list given in head, appending tail.
807 * That allows us to build lists in reverse order, then reverse them
808 * afterwards. This can be faster than building the list in proper
809 * order right away. The reason is that building in proper order
810 * requires writing a link in the _previous_ element, while building
811 * in reverse order just requires placing the list head into the
812 * _current_ element.
1732a1fd 813 */
cee7f245 814
7e6ac6e4
DK
815static struct blame_entry *reverse_blame(struct blame_entry *head,
816 struct blame_entry *tail)
cee7f245 817{
7e6ac6e4
DK
818 while (head) {
819 struct blame_entry *next = head->next;
820 head->next = tail;
821 tail = head;
822 head = next;
cee7f245 823 }
7e6ac6e4 824 return tail;
cee7f245
JH
825}
826
1732a1fd
JH
827/*
828 * Process one hunk from the patch between the current suspect for
7e6ac6e4
DK
829 * blame_entry e and its parent. This first blames any unfinished
830 * entries before the chunk (which is where target and parent start
831 * differing) on the parent, and then splits blame entries at the
832 * start and at the end of the difference region. Since use of -M and
833 * -C options may lead to overlapping/duplicate source line number
834 * ranges, all we can rely on from sorting/merging is the order of the
835 * first suspect line number.
1732a1fd 836 */
7e6ac6e4
DK
837static void blame_chunk(struct blame_entry ***dstq, struct blame_entry ***srcq,
838 int tlno, int offset, int same,
839 struct origin *parent)
cee7f245 840{
7e6ac6e4
DK
841 struct blame_entry *e = **srcq;
842 struct blame_entry *samep = NULL, *diffp = NULL;
cee7f245 843
7e6ac6e4
DK
844 while (e && e->s_lno < tlno) {
845 struct blame_entry *next = e->next;
846 /*
847 * current record starts before differing portion. If
848 * it reaches into it, we need to split it up and
849 * examine the second part separately.
850 */
851 if (e->s_lno + e->num_lines > tlno) {
852 /* Move second half to a new record */
853 int len = tlno - e->s_lno;
854 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
855 n->suspect = e->suspect;
856 n->lno = e->lno + len;
857 n->s_lno = e->s_lno + len;
858 n->num_lines = e->num_lines - len;
859 e->num_lines = len;
860 e->score = 0;
861 /* Push new record to diffp */
862 n->next = diffp;
863 diffp = n;
864 } else
865 origin_decref(e->suspect);
866 /* Pass blame for everything before the differing
867 * chunk to the parent */
868 e->suspect = origin_incref(parent);
869 e->s_lno += offset;
870 e->next = samep;
871 samep = e;
872 e = next;
873 }
874 /*
875 * As we don't know how much of a common stretch after this
876 * diff will occur, the currently blamed parts are all that we
877 * can assign to the parent for now.
878 */
879
880 if (samep) {
881 **dstq = reverse_blame(samep, **dstq);
882 *dstq = &samep->next;
cee7f245 883 }
7e6ac6e4
DK
884 /*
885 * Prepend the split off portions: everything after e starts
886 * after the blameable portion.
887 */
888 e = reverse_blame(diffp, e);
889
890 /*
891 * Now retain records on the target while parts are different
892 * from the parent.
893 */
894 samep = NULL;
895 diffp = NULL;
896 while (e && e->s_lno < same) {
897 struct blame_entry *next = e->next;
898
899 /*
900 * If current record extends into sameness, need to split.
901 */
902 if (e->s_lno + e->num_lines > same) {
903 /*
904 * Move second half to a new record to be
905 * processed by later chunks
906 */
907 int len = same - e->s_lno;
908 struct blame_entry *n = xcalloc(1, sizeof (struct blame_entry));
909 n->suspect = origin_incref(e->suspect);
910 n->lno = e->lno + len;
911 n->s_lno = e->s_lno + len;
912 n->num_lines = e->num_lines - len;
913 e->num_lines = len;
914 e->score = 0;
915 /* Push new record to samep */
916 n->next = samep;
917 samep = n;
918 }
919 e->next = diffp;
920 diffp = e;
921 e = next;
922 }
923 **srcq = reverse_blame(diffp, reverse_blame(samep, e));
924 /* Move across elements that are in the unblamable portion */
925 if (diffp)
926 *srcq = &diffp->next;
cee7f245
JH
927}
928
cdcab133 929struct blame_chunk_cb_data {
cdcab133 930 struct origin *parent;
7e6ac6e4
DK
931 long offset;
932 struct blame_entry **dstq;
933 struct blame_entry **srcq;
cdcab133
RS
934};
935
7e6ac6e4 936/* diff chunks are from parent to target */
0af596c6
RS
937static int blame_chunk_cb(long start_a, long count_a,
938 long start_b, long count_b, void *data)
cdcab133
RS
939{
940 struct blame_chunk_cb_data *d = data;
7e6ac6e4
DK
941 if (start_a - start_b != d->offset)
942 die("internal error in blame::blame_chunk_cb");
943 blame_chunk(&d->dstq, &d->srcq, start_b, start_a - start_b,
944 start_b + count_b, d->parent);
945 d->offset = start_a + count_a - (start_b + count_b);
0af596c6 946 return 0;
cdcab133
RS
947}
948
1732a1fd
JH
949/*
950 * We are looking at the origin 'target' and aiming to pass blame
951 * for the lines it is suspected to its parent. Run diff to find
952 * which lines came from parent and pass blame for them.
953 */
7e6ac6e4
DK
954static void pass_blame_to_parent(struct scoreboard *sb,
955 struct origin *target,
956 struct origin *parent)
cee7f245 957{
7c4ed8c8 958 mmfile_t file_p, file_o;
66dbfd55 959 struct blame_chunk_cb_data d;
7e6ac6e4 960 struct blame_entry *newdest = NULL;
0af596c6 961
7e6ac6e4
DK
962 if (!target->suspects)
963 return; /* nothing remains for this target */
964
965 d.parent = parent;
966 d.offset = 0;
967 d.dstq = &newdest; d.srcq = &target->suspects;
cee7f245 968
3b8a12e8
AB
969 fill_origin_blob(&sb->revs->diffopt, parent, &file_p);
970 fill_origin_blob(&sb->revs->diffopt, target, &file_o);
7c4ed8c8 971 num_get_patch++;
cee7f245 972
17a07e2a 973 if (diff_hunks(&file_p, &file_o, blame_chunk_cb, &d))
3efb9880 974 die("unable to generate diff (%s -> %s)",
f2fd0760 975 oid_to_hex(&parent->commit->object.oid),
976 oid_to_hex(&target->commit->object.oid));
7e6ac6e4
DK
977 /* The rest are the same as the parent */
978 blame_chunk(&d.dstq, &d.srcq, INT_MAX, d.offset, INT_MAX, parent);
979 *d.dstq = NULL;
980 queue_blames(sb, parent, newdest);
cee7f245 981
7e6ac6e4 982 return;
cee7f245
JH
983}
984
1732a1fd
JH
985/*
986 * The lines in blame_entry after splitting blames many times can become
987 * very small and trivial, and at some point it becomes pointless to
988 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
989 * ordinary C program, and it is not worth to say it was copied from
990 * totally unrelated file in the parent.
991 *
992 * Compute how trivial the lines in the blame_entry are.
993 */
5ff62c30
JH
994static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
995{
996 unsigned score;
997 const char *cp, *ep;
998
999 if (e->score)
1000 return e->score;
1001
612702e8 1002 score = 1;
5ff62c30
JH
1003 cp = nth_line(sb, e->lno);
1004 ep = nth_line(sb, e->lno + e->num_lines);
1005 while (cp < ep) {
1006 unsigned ch = *((unsigned char *)cp);
1007 if (isalnum(ch))
1008 score++;
1009 cp++;
1010 }
1011 e->score = score;
1012 return score;
1013}
1014
1732a1fd
JH
1015/*
1016 * best_so_far[] and this[] are both a split of an existing blame_entry
1017 * that passes blame to the parent. Maintain best_so_far the best split
1018 * so far, by comparing this and best_so_far and copying this into
1019 * bst_so_far as needed.
1020 */
5ff62c30 1021static void copy_split_if_better(struct scoreboard *sb,
54a4c617
JH
1022 struct blame_entry *best_so_far,
1023 struct blame_entry *this)
d24bba80 1024{
54a4c617
JH
1025 int i;
1026
d24bba80
JH
1027 if (!this[1].suspect)
1028 return;
5ff62c30
JH
1029 if (best_so_far[1].suspect) {
1030 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
1031 return;
1032 }
54a4c617
JH
1033
1034 for (i = 0; i < 3; i++)
1035 origin_incref(this[i].suspect);
1036 decref_split(best_so_far);
d24bba80
JH
1037 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
1038}
1039
dd166aa8
JH
1040/*
1041 * We are looking at a part of the final image represented by
1042 * ent (tlno and same are offset by ent->s_lno).
1043 * tlno is where we are looking at in the final image.
1044 * up to (but not including) same match preimage.
1045 * plno is where we are looking at in the preimage.
1046 *
1047 * <-------------- final image ---------------------->
1048 * <------ent------>
1049 * ^tlno ^same
1050 * <---------preimage----->
1051 * ^plno
1052 *
1053 * All line numbers are 0-based.
1054 */
1055static void handle_split(struct scoreboard *sb,
1056 struct blame_entry *ent,
1057 int tlno, int plno, int same,
1058 struct origin *parent,
1059 struct blame_entry *split)
1060{
1061 if (ent->num_lines <= tlno)
1062 return;
1063 if (tlno < same) {
1064 struct blame_entry this[3];
1065 tlno += ent->s_lno;
1066 same += ent->s_lno;
1067 split_overlap(this, ent, tlno, plno, same, parent);
1068 copy_split_if_better(sb, split, this);
1069 decref_split(this);
1070 }
1071}
1072
cdcab133
RS
1073struct handle_split_cb_data {
1074 struct scoreboard *sb;
1075 struct blame_entry *ent;
1076 struct origin *parent;
1077 struct blame_entry *split;
1078 long plno;
1079 long tlno;
1080};
1081
5d23ec76
RS
1082static int handle_split_cb(long start_a, long count_a,
1083 long start_b, long count_b, void *data)
cdcab133
RS
1084{
1085 struct handle_split_cb_data *d = data;
5d23ec76
RS
1086 handle_split(d->sb, d->ent, d->tlno, d->plno, start_b, d->parent,
1087 d->split);
1088 d->plno = start_a + count_a;
1089 d->tlno = start_b + count_b;
1090 return 0;
cdcab133
RS
1091}
1092
1732a1fd
JH
1093/*
1094 * Find the lines from parent that are the same as ent so that
1095 * we can pass blames to it. file_p has the blob contents for
1096 * the parent.
1097 */
d24bba80
JH
1098static void find_copy_in_blob(struct scoreboard *sb,
1099 struct blame_entry *ent,
1100 struct origin *parent,
54a4c617 1101 struct blame_entry *split,
d24bba80
JH
1102 mmfile_t *file_p)
1103{
1104 const char *cp;
d24bba80 1105 mmfile_t file_o;
66dbfd55 1106 struct handle_split_cb_data d;
5d23ec76 1107
66dbfd55
GV
1108 memset(&d, 0, sizeof(d));
1109 d.sb = sb; d.ent = ent; d.parent = parent; d.split = split;
1732a1fd
JH
1110 /*
1111 * Prepare mmfile that contains only the lines in ent.
1112 */
d24bba80 1113 cp = nth_line(sb, ent->lno);
4b25d091 1114 file_o.ptr = (char *) cp;
3ee8944f 1115 file_o.size = nth_line(sb, ent->lno + ent->num_lines) - cp;
d24bba80 1116
dd166aa8
JH
1117 /*
1118 * file_o is a part of final image we are annotating.
1119 * file_p partially may match that image.
1120 */
d24bba80 1121 memset(split, 0, sizeof(struct blame_entry [3]));
17a07e2a 1122 if (diff_hunks(file_p, &file_o, handle_split_cb, &d))
3efb9880 1123 die("unable to generate diff (%s)",
f2fd0760 1124 oid_to_hex(&parent->commit->object.oid));
dd166aa8 1125 /* remainder, if any, all match the preimage */
cdcab133 1126 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
d24bba80
JH
1127}
1128
7e6ac6e4
DK
1129/* Move all blame entries from list *source that have a score smaller
1130 * than score_min to the front of list *small.
1131 * Returns a pointer to the link pointing to the old head of the small list.
1132 */
1133
1134static struct blame_entry **filter_small(struct scoreboard *sb,
1135 struct blame_entry **small,
1136 struct blame_entry **source,
1137 unsigned score_min)
1138{
1139 struct blame_entry *p = *source;
1140 struct blame_entry *oldsmall = *small;
1141 while (p) {
1142 if (ent_score(sb, p) <= score_min) {
1143 *small = p;
1144 small = &p->next;
1145 p = *small;
1146 } else {
1147 *source = p;
1148 source = &p->next;
1149 p = *source;
1150 }
1151 }
1152 *small = oldsmall;
1153 *source = NULL;
1154 return small;
1155}
1156
1732a1fd
JH
1157/*
1158 * See if lines currently target is suspected for can be attributed to
1159 * parent.
1160 */
7e6ac6e4
DK
1161static void find_move_in_parent(struct scoreboard *sb,
1162 struct blame_entry ***blamed,
1163 struct blame_entry **toosmall,
1164 struct origin *target,
1165 struct origin *parent)
d24bba80 1166{
46014766 1167 struct blame_entry *e, split[3];
7e6ac6e4
DK
1168 struct blame_entry *unblamed = target->suspects;
1169 struct blame_entry *leftover = NULL;
d24bba80 1170 mmfile_t file_p;
d24bba80 1171
7e6ac6e4
DK
1172 if (!unblamed)
1173 return; /* nothing remains for this target */
d24bba80 1174
3b8a12e8 1175 fill_origin_blob(&sb->revs->diffopt, parent, &file_p);
c2e525d9 1176 if (!file_p.ptr)
7e6ac6e4 1177 return;
d24bba80 1178
7e6ac6e4
DK
1179 /* At each iteration, unblamed has a NULL-terminated list of
1180 * entries that have not yet been tested for blame. leftover
1181 * contains the reversed list of entries that have been tested
1182 * without being assignable to the parent.
1183 */
1184 do {
1185 struct blame_entry **unblamedtail = &unblamed;
1186 struct blame_entry *next;
1187 for (e = unblamed; e; e = next) {
1188 next = e->next;
650e2f67
JH
1189 find_copy_in_blob(sb, e, parent, split, &file_p);
1190 if (split[1].suspect &&
1191 blame_move_score < ent_score(sb, &split[1])) {
7e6ac6e4
DK
1192 split_blame(blamed, &unblamedtail, split, e);
1193 } else {
1194 e->next = leftover;
1195 leftover = e;
650e2f67
JH
1196 }
1197 decref_split(split);
1198 }
7e6ac6e4
DK
1199 *unblamedtail = NULL;
1200 toosmall = filter_small(sb, toosmall, &unblamed, blame_move_score);
1201 } while (unblamed);
1202 target->suspects = reverse_blame(leftover, NULL);
d24bba80
JH
1203}
1204
33494784
JH
1205struct blame_list {
1206 struct blame_entry *ent;
1207 struct blame_entry split[3];
1208};
1209
1732a1fd
JH
1210/*
1211 * Count the number of entries the target is suspected for,
1212 * and prepare a list of entry and the best split.
1213 */
7e6ac6e4 1214static struct blame_list *setup_blame_list(struct blame_entry *unblamed,
33494784
JH
1215 int *num_ents_p)
1216{
1217 struct blame_entry *e;
1218 int num_ents, i;
1219 struct blame_list *blame_list = NULL;
1220
7e6ac6e4
DK
1221 for (e = unblamed, num_ents = 0; e; e = e->next)
1222 num_ents++;
33494784
JH
1223 if (num_ents) {
1224 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
7e6ac6e4
DK
1225 for (e = unblamed, i = 0; e; e = e->next)
1226 blame_list[i++].ent = e;
33494784
JH
1227 }
1228 *num_ents_p = num_ents;
1229 return blame_list;
1230}
1231
1732a1fd
JH
1232/*
1233 * For lines target is suspected for, see if we can find code movement
1234 * across file boundary from the parent commit. porigin is the path
1235 * in the parent we already tried.
1236 */
7e6ac6e4
DK
1237static void find_copy_in_parent(struct scoreboard *sb,
1238 struct blame_entry ***blamed,
1239 struct blame_entry **toosmall,
1240 struct origin *target,
1241 struct commit *parent,
1242 struct origin *porigin,
1243 int opt)
18abd745
JH
1244{
1245 struct diff_options diff_opts;
aec8fa1f 1246 int i, j;
33494784 1247 struct blame_list *blame_list;
aec8fa1f 1248 int num_ents;
7e6ac6e4
DK
1249 struct blame_entry *unblamed = target->suspects;
1250 struct blame_entry *leftover = NULL;
18abd745 1251
7e6ac6e4
DK
1252 if (!unblamed)
1253 return; /* nothing remains for this target */
18abd745
JH
1254
1255 diff_setup(&diff_opts);
8f67f8ae 1256 DIFF_OPT_SET(&diff_opts, RECURSIVE);
18abd745
JH
1257 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1258
28452655 1259 diff_setup_done(&diff_opts);
33494784
JH
1260
1261 /* Try "find copies harder" on new path if requested;
1262 * we do not want to use diffcore_rename() actually to
1263 * match things up; find_copies_harder is set only to
1264 * force diff_tree_sha1() to feed all filepairs to diff_queue,
1265 * and this code needs to be after diff_setup_done(), which
1266 * usually makes find-copies-harder imply copy detection.
1267 */
c63777c0
JH
1268 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1269 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1270 && (!porigin || strcmp(target->path, porigin->path))))
8f67f8ae 1271 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
33494784 1272
f2fd0760 1273 if (is_null_oid(&target->commit->object.oid))
ed1c9977 1274 do_diff_cache(parent->tree->object.oid.hash, &diff_opts);
1cfe7733 1275 else
ed1c9977 1276 diff_tree_sha1(parent->tree->object.oid.hash,
1277 target->commit->tree->object.oid.hash,
1cfe7733 1278 "", &diff_opts);
18abd745 1279
8f67f8ae 1280 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
33494784 1281 diffcore_std(&diff_opts);
18abd745 1282
7e6ac6e4
DK
1283 do {
1284 struct blame_entry **unblamedtail = &unblamed;
1285 blame_list = setup_blame_list(unblamed, &num_ents);
33494784
JH
1286
1287 for (i = 0; i < diff_queued_diff.nr; i++) {
1288 struct diff_filepair *p = diff_queued_diff.queue[i];
1289 struct origin *norigin;
1290 mmfile_t file_p;
33494784
JH
1291 struct blame_entry this[3];
1292
1293 if (!DIFF_FILE_VALID(p->one))
1294 continue; /* does not exist in parent */
5209ac4d
AG
1295 if (S_ISGITLINK(p->one->mode))
1296 continue; /* ignore git links */
33494784
JH
1297 if (porigin && !strcmp(p->one->path, porigin->path))
1298 /* find_move already dealt with this path */
1299 continue;
1300
1301 norigin = get_origin(sb, parent, p->one->path);
a0d12c44 1302 hashcpy(norigin->blob_sha1, p->one->oid.hash);
90064710 1303 norigin->mode = p->one->mode;
3b8a12e8 1304 fill_origin_blob(&sb->revs->diffopt, norigin, &file_p);
33494784
JH
1305 if (!file_p.ptr)
1306 continue;
1307
1308 for (j = 0; j < num_ents; j++) {
1309 find_copy_in_blob(sb, blame_list[j].ent,
1310 norigin, this, &file_p);
1311 copy_split_if_better(sb, blame_list[j].split,
1312 this);
1313 decref_split(this);
1314 }
33494784
JH
1315 origin_decref(norigin);
1316 }
18abd745 1317
aec8fa1f 1318 for (j = 0; j < num_ents; j++) {
33494784
JH
1319 struct blame_entry *split = blame_list[j].split;
1320 if (split[1].suspect &&
1321 blame_copy_score < ent_score(sb, &split[1])) {
7e6ac6e4
DK
1322 split_blame(blamed, &unblamedtail, split,
1323 blame_list[j].ent);
1324 } else {
1325 blame_list[j].ent->next = leftover;
1326 leftover = blame_list[j].ent;
33494784
JH
1327 }
1328 decref_split(split);
18abd745 1329 }
33494784 1330 free(blame_list);
7e6ac6e4
DK
1331 *unblamedtail = NULL;
1332 toosmall = filter_small(sb, toosmall, &unblamed, blame_copy_score);
1333 } while (unblamed);
1334 target->suspects = reverse_blame(leftover, NULL);
33494784 1335 diff_flush(&diff_opts);
ed6e8038 1336 clear_pathspec(&diff_opts.pathspec);
18abd745
JH
1337}
1338
1732a1fd
JH
1339/*
1340 * The blobs of origin and porigin exactly match, so everything
c2e525d9
JH
1341 * origin is suspected for can be blamed on the parent.
1342 */
1343static void pass_whole_blame(struct scoreboard *sb,
1344 struct origin *origin, struct origin *porigin)
1345{
7e6ac6e4 1346 struct blame_entry *e, *suspects;
c2e525d9
JH
1347
1348 if (!porigin->file.ptr && origin->file.ptr) {
1349 /* Steal its file */
1350 porigin->file = origin->file;
1351 origin->file.ptr = NULL;
1352 }
7e6ac6e4
DK
1353 suspects = origin->suspects;
1354 origin->suspects = NULL;
1355 for (e = suspects; e; e = e->next) {
c2e525d9
JH
1356 origin_incref(porigin);
1357 origin_decref(e->suspect);
1358 e->suspect = porigin;
1359 }
7e6ac6e4 1360 queue_blames(sb, porigin, suspects);
c2e525d9
JH
1361}
1362
69264f46
JH
1363/*
1364 * We pass blame from the current commit to its parents. We keep saying
1365 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1366 * exonerate ourselves.
1367 */
85af7929 1368static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
69264f46 1369{
95a4fb0e
JK
1370 if (!reverse) {
1371 if (revs->first_parent_only &&
1372 commit->parents &&
1373 commit->parents->next) {
1374 free_commit_list(commit->parents->next);
1375 commit->parents->next = NULL;
1376 }
85af7929 1377 return commit->parents;
95a4fb0e 1378 }
85af7929 1379 return lookup_decoration(&revs->children, &commit->object);
69264f46
JH
1380}
1381
85af7929 1382static int num_scapegoats(struct rev_info *revs, struct commit *commit)
69264f46 1383{
85af7929 1384 struct commit_list *l = first_scapegoat(revs, commit);
4bbaa1eb 1385 return commit_list_count(l);
69264f46
JH
1386}
1387
7e6ac6e4
DK
1388/* Distribute collected unsorted blames to the respected sorted lists
1389 * in the various origins.
1390 */
1391static void distribute_blame(struct scoreboard *sb, struct blame_entry *blamed)
1392{
1393 blamed = blame_sort(blamed, compare_blame_suspect);
1394 while (blamed)
1395 {
1396 struct origin *porigin = blamed->suspect;
1397 struct blame_entry *suspects = NULL;
1398 do {
1399 struct blame_entry *next = blamed->next;
1400 blamed->next = suspects;
1401 suspects = blamed;
1402 blamed = next;
1403 } while (blamed && blamed->suspect == porigin);
1404 suspects = reverse_blame(suspects, NULL);
1405 queue_blames(sb, porigin, suspects);
1406 }
1407}
1408
69264f46 1409#define MAXSG 16
cee7f245 1410
d24bba80 1411static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
cee7f245 1412{
85af7929 1413 struct rev_info *revs = sb->revs;
69264f46 1414 int i, pass, num_sg;
cee7f245 1415 struct commit *commit = origin->commit;
69264f46
JH
1416 struct commit_list *sg;
1417 struct origin *sg_buf[MAXSG];
1418 struct origin *porigin, **sg_origin = sg_buf;
7e6ac6e4
DK
1419 struct blame_entry *toosmall = NULL;
1420 struct blame_entry *blames, **blametail = &blames;
69264f46 1421
85af7929 1422 num_sg = num_scapegoats(revs, commit);
69264f46
JH
1423 if (!num_sg)
1424 goto finish;
1425 else if (num_sg < ARRAY_SIZE(sg_buf))
1426 memset(sg_buf, 0, sizeof(sg_buf));
1427 else
1428 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
cee7f245 1429
69264f46
JH
1430 /*
1431 * The first pass looks for unrenamed path to optimize for
f69e743d
JH
1432 * common cases, then we look for renames in the second pass.
1433 */
3d1aa566 1434 for (pass = 0; pass < 2 - no_whole_file_rename; pass++) {
f69e743d
JH
1435 struct origin *(*find)(struct scoreboard *,
1436 struct commit *, struct origin *);
1437 find = pass ? find_rename : find_origin;
1438
85af7929 1439 for (i = 0, sg = first_scapegoat(revs, commit);
69264f46
JH
1440 i < num_sg && sg;
1441 sg = sg->next, i++) {
1442 struct commit *p = sg->item;
0421d9f8 1443 int j, same;
f69e743d 1444
69264f46 1445 if (sg_origin[i])
f69e743d
JH
1446 continue;
1447 if (parse_commit(p))
1448 continue;
0d981c67 1449 porigin = find(sb, p, origin);
f69e743d
JH
1450 if (!porigin)
1451 continue;
1452 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
c2e525d9 1453 pass_whole_blame(sb, origin, porigin);
f69e743d
JH
1454 origin_decref(porigin);
1455 goto finish;
1456 }
0421d9f8 1457 for (j = same = 0; j < i; j++)
69264f46
JH
1458 if (sg_origin[j] &&
1459 !hashcmp(sg_origin[j]->blob_sha1,
0421d9f8
JH
1460 porigin->blob_sha1)) {
1461 same = 1;
1462 break;
1463 }
1464 if (!same)
69264f46 1465 sg_origin[i] = porigin;
0421d9f8
JH
1466 else
1467 origin_decref(porigin);
cee7f245 1468 }
cee7f245
JH
1469 }
1470
c2e525d9 1471 num_commits++;
85af7929 1472 for (i = 0, sg = first_scapegoat(revs, commit);
69264f46
JH
1473 i < num_sg && sg;
1474 sg = sg->next, i++) {
1475 struct origin *porigin = sg_origin[i];
cee7f245
JH
1476 if (!porigin)
1477 continue;
96e11709
JH
1478 if (!origin->previous) {
1479 origin_incref(porigin);
1480 origin->previous = porigin;
1481 }
7e6ac6e4
DK
1482 pass_blame_to_parent(sb, origin, porigin);
1483 if (!origin->suspects)
54a4c617 1484 goto finish;
cee7f245 1485 }
d24bba80
JH
1486
1487 /*
1732a1fd 1488 * Optionally find moves in parents' files.
d24bba80 1489 */
7e6ac6e4
DK
1490 if (opt & PICKAXE_BLAME_MOVE) {
1491 filter_small(sb, &toosmall, &origin->suspects, blame_move_score);
1492 if (origin->suspects) {
1493 for (i = 0, sg = first_scapegoat(revs, commit);
1494 i < num_sg && sg;
1495 sg = sg->next, i++) {
1496 struct origin *porigin = sg_origin[i];
1497 if (!porigin)
1498 continue;
1499 find_move_in_parent(sb, &blametail, &toosmall, origin, porigin);
1500 if (!origin->suspects)
1501 break;
1502 }
d24bba80 1503 }
7e6ac6e4 1504 }
d24bba80 1505
18abd745 1506 /*
1732a1fd 1507 * Optionally find copies from parents' files.
18abd745 1508 */
7e6ac6e4
DK
1509 if (opt & PICKAXE_BLAME_COPY) {
1510 if (blame_copy_score > blame_move_score)
1511 filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);
1512 else if (blame_copy_score < blame_move_score) {
1513 origin->suspects = blame_merge(origin->suspects, toosmall);
1514 toosmall = NULL;
1515 filter_small(sb, &toosmall, &origin->suspects, blame_copy_score);
1516 }
1517 if (!origin->suspects)
1518 goto finish;
1519
85af7929 1520 for (i = 0, sg = first_scapegoat(revs, commit);
69264f46
JH
1521 i < num_sg && sg;
1522 sg = sg->next, i++) {
1523 struct origin *porigin = sg_origin[i];
7e6ac6e4
DK
1524 find_copy_in_parent(sb, &blametail, &toosmall,
1525 origin, sg->item, porigin, opt);
1526 if (!origin->suspects)
54a4c617 1527 goto finish;
18abd745 1528 }
7e6ac6e4 1529 }
54a4c617 1530
7e6ac6e4
DK
1531finish:
1532 *blametail = NULL;
1533 distribute_blame(sb, blames);
1534 /*
1535 * prepend toosmall to origin->suspects
1536 *
1537 * There is no point in sorting: this ends up on a big
1538 * unsorted list in the caller anyway.
1539 */
1540 if (toosmall) {
1541 struct blame_entry **tail = &toosmall;
1542 while (*tail)
1543 tail = &(*tail)->next;
1544 *tail = origin->suspects;
1545 origin->suspects = toosmall;
1546 }
69264f46
JH
1547 for (i = 0; i < num_sg; i++) {
1548 if (sg_origin[i]) {
1549 drop_origin_blob(sg_origin[i]);
1550 origin_decref(sg_origin[i]);
7c3c7962
JH
1551 }
1552 }
1553 drop_origin_blob(origin);
69264f46
JH
1554 if (sg_buf != sg_origin)
1555 free(sg_origin);
cee7f245
JH
1556}
1557
1732a1fd
JH
1558/*
1559 * Information on commits, used for output.
1560 */
9cba13ca 1561struct commit_info {
ea02ffa3
AP
1562 struct strbuf author;
1563 struct strbuf author_mail;
cee7f245 1564 unsigned long author_time;
ea02ffa3 1565 struct strbuf author_tz;
cee7f245
JH
1566
1567 /* filled only when asked for details */
ea02ffa3
AP
1568 struct strbuf committer;
1569 struct strbuf committer_mail;
cee7f245 1570 unsigned long committer_time;
ea02ffa3 1571 struct strbuf committer_tz;
cee7f245 1572
ea02ffa3 1573 struct strbuf summary;
cee7f245
JH
1574};
1575
1732a1fd
JH
1576/*
1577 * Parse author/committer line in the commit object buffer
1578 */
cee7f245 1579static void get_ac_line(const char *inbuf, const char *what,
ea02ffa3
AP
1580 struct strbuf *name, struct strbuf *mail,
1581 unsigned long *time, struct strbuf *tz)
cee7f245 1582{
3c020bd5 1583 struct ident_split ident;
ea02ffa3
AP
1584 size_t len, maillen, namelen;
1585 char *tmp, *endp;
1586 const char *namebuf, *mailbuf;
cee7f245
JH
1587
1588 tmp = strstr(inbuf, what);
1589 if (!tmp)
1590 goto error_out;
1591 tmp += strlen(what);
1592 endp = strchr(tmp, '\n');
1593 if (!endp)
1594 len = strlen(tmp);
1595 else
1596 len = endp - tmp;
3c020bd5
AP
1597
1598 if (split_ident_line(&ident, tmp, len)) {
cee7f245
JH
1599 error_out:
1600 /* Ugh */
ea02ffa3
AP
1601 tmp = "(unknown)";
1602 strbuf_addstr(name, tmp);
1603 strbuf_addstr(mail, tmp);
1604 strbuf_addstr(tz, tmp);
cee7f245
JH
1605 *time = 0;
1606 return;
1607 }
cee7f245 1608
3c020bd5 1609 namelen = ident.name_end - ident.name_begin;
ea02ffa3 1610 namebuf = ident.name_begin;
cee7f245 1611
ea02ffa3
AP
1612 maillen = ident.mail_end - ident.mail_begin;
1613 mailbuf = ident.mail_begin;
f9567384 1614
de5abe9f
RS
1615 if (ident.date_begin && ident.date_end)
1616 *time = strtoul(ident.date_begin, NULL, 10);
1617 else
1618 *time = 0;
f9567384 1619
de5abe9f
RS
1620 if (ident.tz_begin && ident.tz_end)
1621 strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);
1622 else
1623 strbuf_addstr(tz, "(unknown)");
f9567384 1624
f9567384 1625 /*
d20d654f 1626 * Now, convert both name and e-mail using mailmap
f9567384 1627 */
ea02ffa3
AP
1628 map_user(&mailmap, &mailbuf, &maillen,
1629 &namebuf, &namelen);
1630
1631 strbuf_addf(mail, "<%.*s>", (int)maillen, mailbuf);
1632 strbuf_add(name, namebuf, namelen);
1633}
1634
1635static void commit_info_init(struct commit_info *ci)
1636{
1637
1638 strbuf_init(&ci->author, 0);
1639 strbuf_init(&ci->author_mail, 0);
1640 strbuf_init(&ci->author_tz, 0);
1641 strbuf_init(&ci->committer, 0);
1642 strbuf_init(&ci->committer_mail, 0);
1643 strbuf_init(&ci->committer_tz, 0);
1644 strbuf_init(&ci->summary, 0);
1645}
1646
1647static void commit_info_destroy(struct commit_info *ci)
1648{
1649
1650 strbuf_release(&ci->author);
1651 strbuf_release(&ci->author_mail);
1652 strbuf_release(&ci->author_tz);
1653 strbuf_release(&ci->committer);
1654 strbuf_release(&ci->committer_mail);
1655 strbuf_release(&ci->committer_tz);
1656 strbuf_release(&ci->summary);
cee7f245
JH
1657}
1658
1659static void get_commit_info(struct commit *commit,
1660 struct commit_info *ret,
1661 int detailed)
1662{
1663 int len;
e297cf5a 1664 const char *subject, *encoding;
b000c59b 1665 const char *message;
ea02ffa3
AP
1666
1667 commit_info_init(ret);
cee7f245 1668
e297cf5a 1669 encoding = get_log_output_encoding();
5a10d236 1670 message = logmsg_reencode(commit, NULL, encoding);
69cd8f63 1671 get_ac_line(message, "\nauthor ",
ea02ffa3 1672 &ret->author, &ret->author_mail,
cee7f245
JH
1673 &ret->author_time, &ret->author_tz);
1674
69cd8f63 1675 if (!detailed) {
b66103c3 1676 unuse_commit_buffer(commit, message);
cee7f245 1677 return;
69cd8f63 1678 }
cee7f245 1679
69cd8f63 1680 get_ac_line(message, "\ncommitter ",
ea02ffa3 1681 &ret->committer, &ret->committer_mail,
cee7f245
JH
1682 &ret->committer_time, &ret->committer_tz);
1683
ad98a58b 1684 len = find_commit_subject(message, &subject);
ea02ffa3
AP
1685 if (len)
1686 strbuf_add(&ret->summary, subject, len);
1687 else
f2fd0760 1688 strbuf_addf(&ret->summary, "(%s)", oid_to_hex(&commit->object.oid));
ea02ffa3 1689
b66103c3 1690 unuse_commit_buffer(commit, message);
cee7f245
JH
1691}
1692
1732a1fd
JH
1693/*
1694 * To allow LF and other nonportable characters in pathnames,
1695 * they are c-style quoted as needed.
1696 */
46e5e69d
JH
1697static void write_filename_info(const char *path)
1698{
1699 printf("filename ");
663af342 1700 write_name_quoted(path, stdout, '\n');
46e5e69d
JH
1701}
1702
9991030c
JH
1703/*
1704 * Porcelain/Incremental format wants to show a lot of details per
1705 * commit. Instead of repeating this every line, emit it only once,
e86226e3
JK
1706 * the first time each commit appears in the output (unless the
1707 * user has specifically asked for us to repeat).
9991030c 1708 */
e86226e3 1709static int emit_one_suspect_detail(struct origin *suspect, int repeat)
9991030c
JH
1710{
1711 struct commit_info ci;
1712
e86226e3 1713 if (!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))
9991030c
JH
1714 return 0;
1715
1716 suspect->commit->object.flags |= METAINFO_SHOWN;
1717 get_commit_info(suspect->commit, &ci, 1);
ea02ffa3
AP
1718 printf("author %s\n", ci.author.buf);
1719 printf("author-mail %s\n", ci.author_mail.buf);
9991030c 1720 printf("author-time %lu\n", ci.author_time);
ea02ffa3
AP
1721 printf("author-tz %s\n", ci.author_tz.buf);
1722 printf("committer %s\n", ci.committer.buf);
1723 printf("committer-mail %s\n", ci.committer_mail.buf);
9991030c 1724 printf("committer-time %lu\n", ci.committer_time);
ea02ffa3
AP
1725 printf("committer-tz %s\n", ci.committer_tz.buf);
1726 printf("summary %s\n", ci.summary.buf);
9991030c
JH
1727 if (suspect->commit->object.flags & UNINTERESTING)
1728 printf("boundary\n");
96e11709
JH
1729 if (suspect->previous) {
1730 struct origin *prev = suspect->previous;
f2fd0760 1731 printf("previous %s ", oid_to_hex(&prev->commit->object.oid));
96e11709
JH
1732 write_name_quoted(prev->path, stdout, '\n');
1733 }
ea02ffa3
AP
1734
1735 commit_info_destroy(&ci);
1736
9991030c
JH
1737 return 1;
1738}
1739
1732a1fd 1740/*
7e6ac6e4
DK
1741 * The blame_entry is found to be guilty for the range.
1742 * Show it in incremental output.
1732a1fd 1743 */
aba37f49
ECA
1744static void found_guilty_entry(struct blame_entry *ent,
1745 struct progress_info *pi)
717d1462 1746{
717d1462
LT
1747 if (incremental) {
1748 struct origin *suspect = ent->suspect;
1749
1750 printf("%s %d %d %d\n",
f2fd0760 1751 oid_to_hex(&suspect->commit->object.oid),
717d1462 1752 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
e86226e3 1753 emit_one_suspect_detail(suspect, 0);
46e5e69d 1754 write_filename_info(suspect->path);
06f59e9f 1755 maybe_flush_or_die(stdout, "stdout");
717d1462 1756 }
aba37f49
ECA
1757 pi->blamed_lines += ent->num_lines;
1758 display_progress(pi->progress, pi->blamed_lines);
717d1462
LT
1759}
1760
1732a1fd 1761/*
7e6ac6e4
DK
1762 * The main loop -- while we have blobs with lines whose true origin
1763 * is still unknown, pick one blob, and allow its lines to pass blames
1764 * to its parents. */
85af7929 1765static void assign_blame(struct scoreboard *sb, int opt)
717d1462 1766{
85af7929 1767 struct rev_info *revs = sb->revs;
7e6ac6e4 1768 struct commit *commit = prio_queue_get(&sb->commits);
aba37f49
ECA
1769 struct progress_info pi = { NULL, 0 };
1770
1771 if (show_progress)
1772 pi.progress = start_progress_delay(_("Blaming lines"),
1773 sb->num_lines, 50, 1);
85af7929 1774
7e6ac6e4 1775 while (commit) {
717d1462 1776 struct blame_entry *ent;
7e6ac6e4 1777 struct origin *suspect = commit->util;
717d1462
LT
1778
1779 /* find one suspect to break down */
7e6ac6e4
DK
1780 while (suspect && !suspect->suspects)
1781 suspect = suspect->next;
1782
1783 if (!suspect) {
1784 commit = prio_queue_get(&sb->commits);
1785 continue;
1786 }
1787
1788 assert(commit == suspect->commit);
717d1462 1789
1732a1fd
JH
1790 /*
1791 * We will use this suspect later in the loop,
1792 * so hold onto it in the meantime.
1793 */
717d1462 1794 origin_incref(suspect);
0064053b 1795 parse_commit(commit);
85af7929
JH
1796 if (reverse ||
1797 (!(commit->object.flags & UNINTERESTING) &&
1798 !(revs->max_age != -1 && commit->date < revs->max_age)))
717d1462
LT
1799 pass_blame(sb, suspect, opt);
1800 else {
1801 commit->object.flags |= UNINTERESTING;
1802 if (commit->object.parsed)
1803 mark_parents_uninteresting(commit);
1804 }
1805 /* treat root commit as boundary */
1806 if (!commit->parents && !show_root)
1807 commit->object.flags |= UNINTERESTING;
1808
1809 /* Take responsibility for the remaining entries */
7e6ac6e4
DK
1810 ent = suspect->suspects;
1811 if (ent) {
1812 suspect->guilty = 1;
1813 for (;;) {
1814 struct blame_entry *next = ent->next;
aba37f49 1815 found_guilty_entry(ent, &pi);
7e6ac6e4
DK
1816 if (next) {
1817 ent = next;
1818 continue;
1819 }
1820 ent->next = sb->ent;
1821 sb->ent = suspect->suspects;
1822 suspect->suspects = NULL;
1823 break;
1824 }
1825 }
717d1462
LT
1826 origin_decref(suspect);
1827
1828 if (DEBUG) /* sanity */
1829 sanity_check_refcnt(sb);
1830 }
aba37f49
ECA
1831
1832 stop_progress(&pi.progress);
717d1462
LT
1833}
1834
1835static const char *format_time(unsigned long time, const char *tz_str,
1836 int show_raw_time)
1837{
bccce0f8 1838 static struct strbuf time_buf = STRBUF_INIT;
717d1462 1839
bccce0f8 1840 strbuf_reset(&time_buf);
717d1462 1841 if (show_raw_time) {
bccce0f8 1842 strbuf_addf(&time_buf, "%lu %s", time, tz_str);
717d1462 1843 }
31653c1a 1844 else {
ac39b277 1845 const char *time_str;
bccce0f8 1846 size_t time_width;
ac39b277 1847 int tz;
31653c1a 1848 tz = atoi(tz_str);
a5481a6c 1849 time_str = show_date(time, tz, &blame_date_mode);
bccce0f8
JX
1850 strbuf_addstr(&time_buf, time_str);
1851 /*
1852 * Add space paddings to time_buf to display a fixed width
1853 * string, and use time_width for display width calibration.
1854 */
1855 for (time_width = utf8_strwidth(time_str);
1856 time_width < blame_date_width;
1857 time_width++)
1858 strbuf_addch(&time_buf, ' ');
31653c1a 1859 }
bccce0f8 1860 return time_buf.buf;
717d1462
LT
1861}
1862
cee7f245
JH
1863#define OUTPUT_ANNOTATE_COMPAT 001
1864#define OUTPUT_LONG_OBJECT_NAME 002
1865#define OUTPUT_RAW_TIMESTAMP 004
1866#define OUTPUT_PORCELAIN 010
1867#define OUTPUT_SHOW_NAME 020
1868#define OUTPUT_SHOW_NUMBER 040
5ff62c30 1869#define OUTPUT_SHOW_SCORE 0100
093dc5be 1870#define OUTPUT_NO_AUTHOR 0200
1b8cdce9 1871#define OUTPUT_SHOW_EMAIL 0400
ed747dd5 1872#define OUTPUT_LINE_PORCELAIN 01000
cee7f245 1873
e86226e3
JK
1874static void emit_porcelain_details(struct origin *suspect, int repeat)
1875{
1876 if (emit_one_suspect_detail(suspect, repeat) ||
1877 (suspect->commit->object.flags & MORE_THAN_ONE_PATH))
1878 write_filename_info(suspect->path);
1879}
1880
1881static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent,
1882 int opt)
cee7f245 1883{
ed747dd5 1884 int repeat = opt & OUTPUT_LINE_PORCELAIN;
cee7f245
JH
1885 int cnt;
1886 const char *cp;
1887 struct origin *suspect = ent->suspect;
d59f765a 1888 char hex[GIT_SHA1_HEXSZ + 1];
cee7f245 1889
f2fd0760 1890 sha1_to_hex_r(hex, suspect->commit->object.oid.hash);
7e6ac6e4 1891 printf("%s %d %d %d\n",
cee7f245 1892 hex,
cee7f245
JH
1893 ent->s_lno + 1,
1894 ent->lno + 1,
1895 ent->num_lines);
ed747dd5 1896 emit_porcelain_details(suspect, repeat);
cee7f245
JH
1897
1898 cp = nth_line(sb, ent->lno);
1899 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1900 char ch;
ed747dd5 1901 if (cnt) {
cee7f245
JH
1902 printf("%s %d %d\n", hex,
1903 ent->s_lno + 1 + cnt,
1904 ent->lno + 1 + cnt);
ed747dd5
JK
1905 if (repeat)
1906 emit_porcelain_details(suspect, 1);
1907 }
cee7f245
JH
1908 putchar('\t');
1909 do {
1910 ch = *cp++;
1911 putchar(ch);
1912 } while (ch != '\n' &&
1913 cp < sb->final_buf + sb->final_buf_size);
1914 }
a5ca8367
JS
1915
1916 if (sb->final_buf_size && cp[-1] != '\n')
1917 putchar('\n');
cee7f245
JH
1918}
1919
1920static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1921{
1922 int cnt;
1923 const char *cp;
1924 struct origin *suspect = ent->suspect;
1925 struct commit_info ci;
d59f765a 1926 char hex[GIT_SHA1_HEXSZ + 1];
cee7f245
JH
1927 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1928
1929 get_commit_info(suspect->commit, &ci, 1);
f2fd0760 1930 sha1_to_hex_r(hex, suspect->commit->object.oid.hash);
cee7f245
JH
1931
1932 cp = nth_line(sb, ent->lno);
1933 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1934 char ch;
84393bfd 1935 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : abbrev;
b11121d9
JH
1936
1937 if (suspect->commit->object.flags & UNINTERESTING) {
e68989a7
JH
1938 if (blank_boundary)
1939 memset(hex, ' ', length);
7ceacdff 1940 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
4c10a5ca
JH
1941 length--;
1942 putchar('^');
1943 }
b11121d9 1944 }
cee7f245 1945
b11121d9 1946 printf("%.*s", length, hex);
1b8cdce9
KB
1947 if (opt & OUTPUT_ANNOTATE_COMPAT) {
1948 const char *name;
1949 if (opt & OUTPUT_SHOW_EMAIL)
ea02ffa3 1950 name = ci.author_mail.buf;
1b8cdce9 1951 else
ea02ffa3 1952 name = ci.author.buf;
1b8cdce9 1953 printf("\t(%10s\t%10s\t%d)", name,
ea02ffa3 1954 format_time(ci.author_time, ci.author_tz.buf,
cee7f245
JH
1955 show_raw_time),
1956 ent->lno + 1 + cnt);
1b8cdce9 1957 } else {
5ff62c30 1958 if (opt & OUTPUT_SHOW_SCORE)
54a4c617
JH
1959 printf(" %*d %02d",
1960 max_score_digits, ent->score,
1961 ent->suspect->refcnt);
cee7f245
JH
1962 if (opt & OUTPUT_SHOW_NAME)
1963 printf(" %-*.*s", longest_file, longest_file,
1964 suspect->path);
1965 if (opt & OUTPUT_SHOW_NUMBER)
1966 printf(" %*d", max_orig_digits,
1967 ent->s_lno + 1 + cnt);
093dc5be 1968
ffaf9cc0 1969 if (!(opt & OUTPUT_NO_AUTHOR)) {
1b8cdce9
KB
1970 const char *name;
1971 int pad;
1972 if (opt & OUTPUT_SHOW_EMAIL)
ea02ffa3 1973 name = ci.author_mail.buf;
1b8cdce9 1974 else
ea02ffa3 1975 name = ci.author.buf;
1b8cdce9 1976 pad = longest_author - utf8_strwidth(name);
ffaf9cc0 1977 printf(" (%s%*s %10s",
1b8cdce9 1978 name, pad, "",
093dc5be 1979 format_time(ci.author_time,
ea02ffa3 1980 ci.author_tz.buf,
093dc5be 1981 show_raw_time));
ffaf9cc0 1982 }
093dc5be 1983 printf(" %*d) ",
cee7f245
JH
1984 max_digits, ent->lno + 1 + cnt);
1985 }
1986 do {
1987 ch = *cp++;
1988 putchar(ch);
1989 } while (ch != '\n' &&
1990 cp < sb->final_buf + sb->final_buf_size);
1991 }
a5ca8367
JS
1992
1993 if (sb->final_buf_size && cp[-1] != '\n')
1994 putchar('\n');
ea02ffa3
AP
1995
1996 commit_info_destroy(&ci);
cee7f245
JH
1997}
1998
1999static void output(struct scoreboard *sb, int option)
2000{
2001 struct blame_entry *ent;
2002
2003 if (option & OUTPUT_PORCELAIN) {
2004 for (ent = sb->ent; ent; ent = ent->next) {
7e6ac6e4
DK
2005 int count = 0;
2006 struct origin *suspect;
2007 struct commit *commit = ent->suspect->commit;
cee7f245
JH
2008 if (commit->object.flags & MORE_THAN_ONE_PATH)
2009 continue;
7e6ac6e4
DK
2010 for (suspect = commit->util; suspect; suspect = suspect->next) {
2011 if (suspect->guilty && count++) {
2012 commit->object.flags |= MORE_THAN_ONE_PATH;
2013 break;
2014 }
cee7f245
JH
2015 }
2016 }
2017 }
2018
2019 for (ent = sb->ent; ent; ent = ent->next) {
2020 if (option & OUTPUT_PORCELAIN)
e86226e3 2021 emit_porcelain(sb, ent, option);
5ff62c30 2022 else {
cee7f245 2023 emit_other(sb, ent, option);
5ff62c30 2024 }
cee7f245
JH
2025 }
2026}
2027
29aa0b20
RS
2028static const char *get_next_line(const char *start, const char *end)
2029{
2030 const char *nl = memchr(start, '\n', end - start);
60d85e11 2031 return nl ? nl + 1 : end;
29aa0b20
RS
2032}
2033
1732a1fd
JH
2034/*
2035 * To allow quick access to the contents of nth line in the
2036 * final image, prepare an index in the scoreboard.
2037 */
cee7f245
JH
2038static int prepare_lines(struct scoreboard *sb)
2039{
2040 const char *buf = sb->final_buf;
2041 unsigned long len = sb->final_buf_size;
352bbbd9
DK
2042 const char *end = buf + len;
2043 const char *p;
2044 int *lineno;
60d85e11 2045 int num = 0;
352bbbd9 2046
60d85e11 2047 for (p = buf; p < end; p = get_next_line(p, end))
29aa0b20 2048 num++;
352bbbd9 2049
b32fa95f
JK
2050 ALLOC_ARRAY(sb->lineno, num + 1);
2051 lineno = sb->lineno;
352bbbd9 2052
60d85e11 2053 for (p = buf; p < end; p = get_next_line(p, end))
29aa0b20 2054 *lineno++ = p - buf;
352bbbd9 2055
60d85e11 2056 *lineno = len;
352bbbd9 2057
60d85e11 2058 sb->num_lines = num;
cee7f245
JH
2059 return sb->num_lines;
2060}
2061
1732a1fd
JH
2062/*
2063 * Add phony grafts for use with -S; this is primarily to
34baebce 2064 * support git's cvsserver that wants to give a linear history
1732a1fd
JH
2065 * to its clients.
2066 */
cee7f245
JH
2067static int read_ancestry(const char *graft_file)
2068{
2069 FILE *fp = fopen(graft_file, "r");
e228c173 2070 struct strbuf buf = STRBUF_INIT;
cee7f245
JH
2071 if (!fp)
2072 return -1;
e228c173 2073 while (!strbuf_getwholeline(&buf, fp, '\n')) {
cee7f245 2074 /* The format is just "Commit Parent1 Parent2 ...\n" */
e228c173 2075 struct commit_graft *graft = read_graft_line(buf.buf, buf.len);
8eaf7986
JH
2076 if (graft)
2077 register_commit_graft(graft, 0);
cee7f245
JH
2078 }
2079 fclose(fp);
e228c173 2080 strbuf_release(&buf);
cee7f245
JH
2081 return 0;
2082}
2083
b31272f7
JH
2084static int update_auto_abbrev(int auto_abbrev, struct origin *suspect)
2085{
ed1c9977 2086 const char *uniq = find_unique_abbrev(suspect->commit->object.oid.hash,
b31272f7
JH
2087 auto_abbrev);
2088 int len = strlen(uniq);
2089 if (auto_abbrev < len)
2090 return len;
2091 return auto_abbrev;
2092}
2093
1732a1fd
JH
2094/*
2095 * How many columns do we need to show line numbers, authors,
2096 * and filenames?
2097 */
cee7f245
JH
2098static void find_alignment(struct scoreboard *sb, int *option)
2099{
2100 int longest_src_lines = 0;
2101 int longest_dst_lines = 0;
5ff62c30 2102 unsigned largest_score = 0;
cee7f245 2103 struct blame_entry *e;
b31272f7 2104 int compute_auto_abbrev = (abbrev < 0);
5293284b 2105 int auto_abbrev = DEFAULT_ABBREV;
cee7f245
JH
2106
2107 for (e = sb->ent; e; e = e->next) {
2108 struct origin *suspect = e->suspect;
cee7f245
JH
2109 int num;
2110
b31272f7
JH
2111 if (compute_auto_abbrev)
2112 auto_abbrev = update_auto_abbrev(auto_abbrev, suspect);
ab3bb800
JH
2113 if (strcmp(suspect->path, sb->path))
2114 *option |= OUTPUT_SHOW_NAME;
2115 num = strlen(suspect->path);
2116 if (longest_file < num)
2117 longest_file = num;
cee7f245 2118 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
e6005927 2119 struct commit_info ci;
cee7f245
JH
2120 suspect->commit->object.flags |= METAINFO_SHOWN;
2121 get_commit_info(suspect->commit, &ci, 1);
1b8cdce9 2122 if (*option & OUTPUT_SHOW_EMAIL)
ea02ffa3 2123 num = utf8_strwidth(ci.author_mail.buf);
1b8cdce9 2124 else
ea02ffa3 2125 num = utf8_strwidth(ci.author.buf);
cee7f245
JH
2126 if (longest_author < num)
2127 longest_author = num;
e6005927 2128 commit_info_destroy(&ci);
cee7f245
JH
2129 }
2130 num = e->s_lno + e->num_lines;
2131 if (longest_src_lines < num)
2132 longest_src_lines = num;
2133 num = e->lno + e->num_lines;
2134 if (longest_dst_lines < num)
2135 longest_dst_lines = num;
5ff62c30
JH
2136 if (largest_score < ent_score(sb, e))
2137 largest_score = ent_score(sb, e);
cee7f245 2138 }
ec7ff5ba
ZJS
2139 max_orig_digits = decimal_width(longest_src_lines);
2140 max_digits = decimal_width(longest_dst_lines);
2141 max_score_digits = decimal_width(largest_score);
b31272f7
JH
2142
2143 if (compute_auto_abbrev)
2144 /* one more abbrev length is needed for the boundary commit */
2145 abbrev = auto_abbrev + 1;
cee7f245
JH
2146}
2147
1732a1fd
JH
2148/*
2149 * For debugging -- origin is refcounted, and this asserts that
2150 * we do not underflow.
2151 */
54a4c617
JH
2152static void sanity_check_refcnt(struct scoreboard *sb)
2153{
2154 int baa = 0;
2155 struct blame_entry *ent;
2156
2157 for (ent = sb->ent; ent; ent = ent->next) {
ae86ad65 2158 /* Nobody should have zero or negative refcnt */
854b97f6
JH
2159 if (ent->suspect->refcnt <= 0) {
2160 fprintf(stderr, "%s in %s has negative refcnt %d\n",
2161 ent->suspect->path,
f2fd0760 2162 oid_to_hex(&ent->suspect->commit->object.oid),
854b97f6 2163 ent->suspect->refcnt);
ae86ad65 2164 baa = 1;
854b97f6 2165 }
ae86ad65 2166 }
54a4c617
JH
2167 if (baa) {
2168 int opt = 0160;
2169 find_alignment(sb, &opt);
2170 output(sb, opt);
854b97f6 2171 die("Baa %d!", baa);
54a4c617
JH
2172 }
2173}
2174
4a0fc95f
JH
2175static unsigned parse_score(const char *arg)
2176{
2177 char *end;
2178 unsigned long score = strtoul(arg, &end, 10);
2179 if (*end)
2180 return 0;
2181 return score;
2182}
2183
20239bae
JK
2184static const char *add_prefix(const char *prefix, const char *path)
2185{
097971f5 2186 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
20239bae
JK
2187}
2188
ef90d6d4 2189static int git_blame_config(const char *var, const char *value, void *cb)
4c10a5ca
JH
2190{
2191 if (!strcmp(var, "blame.showroot")) {
2192 show_root = git_config_bool(var, value);
2193 return 0;
2194 }
2195 if (!strcmp(var, "blame.blankboundary")) {
2196 blank_boundary = git_config_bool(var, value);
2197 return 0;
2198 }
8b504db3
QN
2199 if (!strcmp(var, "blame.showemail")) {
2200 int *output_option = cb;
2201 if (git_config_bool(var, value))
2202 *output_option |= OUTPUT_SHOW_EMAIL;
2203 else
2204 *output_option &= ~OUTPUT_SHOW_EMAIL;
2205 return 0;
2206 }
31653c1a
EL
2207 if (!strcmp(var, "blame.date")) {
2208 if (!value)
2209 return config_error_nonbool(var);
a5481a6c 2210 parse_date_format(value, &blame_date_mode);
31653c1a
EL
2211 return 0;
2212 }
3b8a12e8 2213
6680a087 2214 if (userdiff_config(var, value) < 0)
3b8a12e8 2215 return -1;
3b8a12e8 2216
ef90d6d4 2217 return git_default_config(var, value, cb);
4c10a5ca
JH
2218}
2219
9aeaab68 2220static void verify_working_tree_path(struct commit *work_tree, const char *path)
ffcabccf 2221{
9aeaab68 2222 struct commit_list *parents;
3b75ee93 2223 int pos;
ffcabccf 2224
9aeaab68 2225 for (parents = work_tree->parents; parents; parents = parents->next) {
ed1c9977 2226 const unsigned char *commit_sha1 = parents->item->object.oid.hash;
9aeaab68
JH
2227 unsigned char blob_sha1[20];
2228 unsigned mode;
2229
2230 if (!get_tree_entry(commit_sha1, path, blob_sha1, &mode) &&
2231 sha1_object_info(blob_sha1, NULL) == OBJ_BLOB)
2232 return;
2233 }
3b75ee93
MH
2234
2235 pos = cache_name_pos(path, strlen(path));
2236 if (pos >= 0)
2237 ; /* path is in the index */
bc6b13a7
TG
2238 else if (-1 - pos < active_nr &&
2239 !strcmp(active_cache[-1 - pos]->name, path))
3b75ee93
MH
2240 ; /* path is in the index, unmerged */
2241 else
2242 die("no such path '%s' in HEAD", path);
9aeaab68
JH
2243}
2244
2245static struct commit_list **append_parent(struct commit_list **tail, const unsigned char *sha1)
2246{
2247 struct commit *parent;
2248
2249 parent = lookup_commit_reference(sha1);
2250 if (!parent)
2251 die("no such commit %s", sha1_to_hex(sha1));
2252 return &commit_list_insert(parent, tail)->next;
2253}
2254
2255static void append_merge_parents(struct commit_list **tail)
2256{
2257 int merge_head;
9aeaab68
JH
2258 struct strbuf line = STRBUF_INIT;
2259
f932729c 2260 merge_head = open(git_path_merge_head(), O_RDONLY);
9aeaab68
JH
2261 if (merge_head < 0) {
2262 if (errno == ENOENT)
2263 return;
f932729c 2264 die("cannot open '%s' for reading", git_path_merge_head());
9aeaab68
JH
2265 }
2266
2267 while (!strbuf_getwholeline_fd(&line, merge_head, '\n')) {
2268 unsigned char sha1[20];
2269 if (line.len < 40 || get_sha1_hex(line.buf, sha1))
f932729c 2270 die("unknown line in '%s': %s", git_path_merge_head(), line.buf);
9aeaab68
JH
2271 tail = append_parent(tail, sha1);
2272 }
2273 close(merge_head);
2274 strbuf_release(&line);
ffcabccf
JH
2275}
2276
8597ea3a
JK
2277/*
2278 * This isn't as simple as passing sb->buf and sb->len, because we
2279 * want to transfer ownership of the buffer to the commit (so we
2280 * must use detach).
2281 */
2282static void set_commit_buffer_from_strbuf(struct commit *c, struct strbuf *sb)
2283{
2284 size_t len;
2285 void *buf = strbuf_detach(sb, &len);
2286 set_commit_buffer(c, buf, len);
2287}
2288
f6c07d7d
JH
2289/*
2290 * Prepare a dummy commit that represents the work tree (or staged) item.
2291 * Note that annotating work tree item never works in the reverse.
2292 */
3b8a12e8
AB
2293static struct commit *fake_working_tree_commit(struct diff_options *opt,
2294 const char *path,
2295 const char *contents_from)
1cfe7733
JH
2296{
2297 struct commit *commit;
2298 struct origin *origin;
9aeaab68 2299 struct commit_list **parent_tail, *parent;
1cfe7733 2300 unsigned char head_sha1[20];
f285a2d7 2301 struct strbuf buf = STRBUF_INIT;
1cfe7733 2302 const char *ident;
1cfe7733 2303 time_t now;
1cfe7733
JH
2304 int size, len;
2305 struct cache_entry *ce;
2306 unsigned mode;
9aeaab68 2307 struct strbuf msg = STRBUF_INIT;
1cfe7733 2308
a08feb8e 2309 read_cache();
1cfe7733 2310 time(&now);
10322a0a 2311 commit = alloc_commit_node();
1cfe7733
JH
2312 commit->object.parsed = 1;
2313 commit->date = now;
9aeaab68
JH
2314 parent_tail = &commit->parents;
2315
7695d118 2316 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, head_sha1, NULL))
9aeaab68
JH
2317 die("no such ref: HEAD");
2318
2319 parent_tail = append_parent(parent_tail, head_sha1);
2320 append_merge_parents(parent_tail);
2321 verify_working_tree_path(commit, path);
1cfe7733
JH
2322
2323 origin = make_origin(commit, path);
2324
9aeaab68
JH
2325 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
2326 strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
2327 for (parent = commit->parents; parent; parent = parent->next)
2328 strbuf_addf(&msg, "parent %s\n",
f2fd0760 2329 oid_to_hex(&parent->item->object.oid));
9aeaab68
JH
2330 strbuf_addf(&msg,
2331 "author %s\n"
2332 "committer %s\n\n"
2333 "Version of %s from %s\n",
2334 ident, ident, path,
2335 (!contents_from ? path :
2336 (!strcmp(contents_from, "-") ? "standard input" : contents_from)));
8597ea3a 2337 set_commit_buffer_from_strbuf(commit, &msg);
9aeaab68 2338
1cfe7733
JH
2339 if (!contents_from || strcmp("-", contents_from)) {
2340 struct stat st;
2341 const char *read_from;
8518088f 2342 char *buf_ptr;
3b8a12e8 2343 unsigned long buf_len;
1cfe7733
JH
2344
2345 if (contents_from) {
2346 if (stat(contents_from, &st) < 0)
0721c314 2347 die_errno("Cannot stat '%s'", contents_from);
1cfe7733
JH
2348 read_from = contents_from;
2349 }
2350 else {
2351 if (lstat(path, &st) < 0)
0721c314 2352 die_errno("Cannot lstat '%s'", path);
1cfe7733
JH
2353 read_from = path;
2354 }
1cfe7733 2355 mode = canon_mode(st.st_mode);
3b8a12e8 2356
1cfe7733
JH
2357 switch (st.st_mode & S_IFMT) {
2358 case S_IFREG:
3b8a12e8 2359 if (DIFF_OPT_TST(opt, ALLOW_TEXTCONV) &&
e5450100 2360 textconv_object(read_from, mode, null_sha1, 0, &buf_ptr, &buf_len))
8518088f 2361 strbuf_attach(&buf, buf_ptr, buf_len, buf_len + 1);
3b8a12e8 2362 else if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
0721c314 2363 die_errno("cannot open or read '%s'", read_from);
1cfe7733
JH
2364 break;
2365 case S_IFLNK:
edfd45d2 2366 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
0721c314 2367 die_errno("cannot readlink '%s'", read_from);
1cfe7733
JH
2368 break;
2369 default:
2370 die("unsupported file type %s", read_from);
2371 }
2372 }
2373 else {
2374 /* Reading from stdin */
1cfe7733 2375 mode = 0;
f1696ee3 2376 if (strbuf_read(&buf, 0, 0) < 0)
d824cbba 2377 die_errno("failed to read from stdin");
1cfe7733 2378 }
4bf256d6 2379 convert_to_git(path, buf.buf, buf.len, &buf, 0);
af6eb822
PH
2380 origin->file.ptr = buf.buf;
2381 origin->file.size = buf.len;
2382 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
1cfe7733
JH
2383
2384 /*
2385 * Read the current index, replace the path entry with
2386 * origin->blob_sha1 without mucking with its mode or type
2387 * bits; we are not going to write this index out -- we just
2388 * want to run "diff-index --cached".
2389 */
2390 discard_cache();
2391 read_cache();
2392
2393 len = strlen(path);
2394 if (!mode) {
2395 int pos = cache_name_pos(path, len);
2396 if (0 <= pos)
7a51ed66 2397 mode = active_cache[pos]->ce_mode;
1cfe7733
JH
2398 else
2399 /* Let's not bother reading from HEAD tree */
2400 mode = S_IFREG | 0644;
2401 }
2402 size = cache_entry_size(len);
2403 ce = xcalloc(1, size);
2404 hashcpy(ce->sha1, origin->blob_sha1);
2405 memcpy(ce->name, path, len);
b60e188c
TG
2406 ce->ce_flags = create_ce_flags(0);
2407 ce->ce_namelen = len;
1cfe7733
JH
2408 ce->ce_mode = create_ce_mode(mode);
2409 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2410
a5400efe 2411 cache_tree_invalidate_path(&the_index, path);
1cfe7733 2412
1cfe7733
JH
2413 return commit;
2414}
2415
7cb5f7c4
JK
2416static struct commit *find_single_final(struct rev_info *revs,
2417 const char **name_p)
f6c07d7d
JH
2418{
2419 int i;
7cb5f7c4
JK
2420 struct commit *found = NULL;
2421 const char *name = NULL;
f6c07d7d 2422
f6c07d7d
JH
2423 for (i = 0; i < revs->pending.nr; i++) {
2424 struct object *obj = revs->pending.objects[i].item;
2425 if (obj->flags & UNINTERESTING)
2426 continue;
31da121f 2427 obj = deref_tag(obj, NULL, 0);
f6c07d7d
JH
2428 if (obj->type != OBJ_COMMIT)
2429 die("Non commit %s?", revs->pending.objects[i].name);
1b0d4000 2430 if (found)
f6c07d7d 2431 die("More than one commit to dig from %s and %s?",
7cb5f7c4
JK
2432 revs->pending.objects[i].name, name);
2433 found = (struct commit *)obj;
2434 name = revs->pending.objects[i].name;
1b0d4000 2435 }
7cb5f7c4
JK
2436 if (name_p)
2437 *name_p = name;
1b0d4000
MK
2438 return found;
2439}
2440
2441static char *prepare_final(struct scoreboard *sb)
2442{
7cb5f7c4
JK
2443 const char *name;
2444 sb->final = find_single_final(sb->revs, &name);
2445 return xstrdup_or_null(name);
f6c07d7d
JH
2446}
2447
a46442f1 2448static char *prepare_initial(struct scoreboard *sb)
85af7929
JH
2449{
2450 int i;
2451 const char *final_commit_name = NULL;
2452 struct rev_info *revs = sb->revs;
2453
2454 /*
2455 * There must be one and only one negative commit, and it must be
2456 * the boundary.
2457 */
2458 for (i = 0; i < revs->pending.nr; i++) {
2459 struct object *obj = revs->pending.objects[i].item;
2460 if (!(obj->flags & UNINTERESTING))
2461 continue;
31da121f 2462 obj = deref_tag(obj, NULL, 0);
85af7929
JH
2463 if (obj->type != OBJ_COMMIT)
2464 die("Non commit %s?", revs->pending.objects[i].name);
2465 if (sb->final)
2466 die("More than one commit to dig down to %s and %s?",
2467 revs->pending.objects[i].name,
2468 final_commit_name);
2469 sb->final = (struct commit *) obj;
2470 final_commit_name = revs->pending.objects[i].name;
2471 }
2472 if (!final_commit_name)
2473 die("No commit to dig down to?");
a46442f1 2474 return xstrdup(final_commit_name);
85af7929
JH
2475}
2476
5817da01
PH
2477static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2478{
2479 int *opt = option->value;
2480
2481 /*
2482 * -C enables copy from removed files;
2483 * -C -C enables copy from existing files, but only
2484 * when blaming a new file;
2485 * -C -C -C enables copy from existing files for
2486 * everybody
2487 */
2488 if (*opt & PICKAXE_BLAME_COPY_HARDER)
2489 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2490 if (*opt & PICKAXE_BLAME_COPY)
2491 *opt |= PICKAXE_BLAME_COPY_HARDER;
2492 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2493
2494 if (arg)
2495 blame_copy_score = parse_score(arg);
2496 return 0;
2497}
2498
2499static int blame_move_callback(const struct option *option, const char *arg, int unset)
2500{
2501 int *opt = option->value;
2502
2503 *opt |= PICKAXE_BLAME_MOVE;
2504
2505 if (arg)
2506 blame_move_score = parse_score(arg);
2507 return 0;
2508}
2509
acca687f 2510int cmd_blame(int argc, const char **argv, const char *prefix)
cee7f245
JH
2511{
2512 struct rev_info revs;
2513 const char *path;
2514 struct scoreboard sb;
2515 struct origin *o;
58dbfa2e
ES
2516 struct blame_entry *ent = NULL;
2517 long dashdash_pos, lno;
a46442f1 2518 char *final_commit_name = NULL;
21666f1a 2519 enum object_type type;
700fd28e 2520 struct commit *final_commit = NULL;
5817da01 2521
64093fc0
JK
2522 struct string_list range_list = STRING_LIST_INIT_NODUP;
2523 int output_option = 0, opt = 0;
2524 int show_stats = 0;
2525 const char *revs_file = NULL;
2526 const char *contents_from = NULL;
2527 const struct option options[] = {
d5d09d47
SB
2528 OPT_BOOL(0, "incremental", &incremental, N_("Show blame entries as we find them, incrementally")),
2529 OPT_BOOL('b', NULL, &blank_boundary, N_("Show blank SHA-1 for boundary commits (Default: off)")),
2530 OPT_BOOL(0, "root", &show_root, N_("Do not treat root commits as boundaries (Default: off)")),
2531 OPT_BOOL(0, "show-stats", &show_stats, N_("Show work cost statistics")),
aba37f49 2532 OPT_BOOL(0, "progress", &show_progress, N_("Force progress reporting")),
efd2a8bd
NTND
2533 OPT_BIT(0, "score-debug", &output_option, N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),
2534 OPT_BIT('f', "show-name", &output_option, N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),
2535 OPT_BIT('n', "show-number", &output_option, N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),
2536 OPT_BIT('p', "porcelain", &output_option, N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),
2537 OPT_BIT(0, "line-porcelain", &output_option, N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),
2538 OPT_BIT('c', NULL, &output_option, N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),
2539 OPT_BIT('t', NULL, &output_option, N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),
2540 OPT_BIT('l', NULL, &output_option, N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),
2541 OPT_BIT('s', NULL, &output_option, N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),
2542 OPT_BIT('e', "show-email", &output_option, N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),
2543 OPT_BIT('w', NULL, &xdl_opts, N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),
2544 OPT_BIT(0, "minimal", &xdl_opts, N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),
2545 OPT_STRING('S', NULL, &revs_file, N_("file"), N_("Use revisions from <file> instead of calling git-rev-list")),
2546 OPT_STRING(0, "contents", &contents_from, N_("file"), N_("Use <file>'s contents as the final image")),
2547 { OPTION_CALLBACK, 'C', NULL, &opt, N_("score"), N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },
2548 { OPTION_CALLBACK, 'M', NULL, &opt, N_("score"), N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },
58dbfa2e 2549 OPT_STRING_LIST('L', NULL, &range_list, N_("n,m"), N_("Process only line range n,m, counting from 1")),
84393bfd 2550 OPT__ABBREV(&abbrev),
5817da01
PH
2551 OPT_END()
2552 };
2553
2554 struct parse_opt_ctx_t ctx;
7ceacdff 2555 int cmd_is_annotate = !strcmp(argv[0], "annotate");
58dbfa2e
ES
2556 struct range_set ranges;
2557 unsigned int range_i;
52f4d126 2558 long anchor;
e68989a7 2559
8b504db3 2560 git_config(git_blame_config, &output_option);
5817da01 2561 init_revisions(&revs, NULL);
31653c1a 2562 revs.date_mode = blame_date_mode;
3b8a12e8 2563 DIFF_OPT_SET(&revs.diffopt, ALLOW_TEXTCONV);
3d1aa566 2564 DIFF_OPT_SET(&revs.diffopt, FOLLOW_RENAMES);
31653c1a 2565
612702e8 2566 save_commit_buffer = 0;
3f8d5204 2567 dashdash_pos = 0;
aba37f49 2568 show_progress = -1;
612702e8 2569
9ca1169f
SB
2570 parse_options_start(&ctx, argc, argv, prefix, options,
2571 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);
5817da01 2572 for (;;) {
5817da01
PH
2573 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2574 case PARSE_OPT_HELP:
2575 exit(129);
2576 case PARSE_OPT_DONE:
3f8d5204
PH
2577 if (ctx.argv[0])
2578 dashdash_pos = ctx.cpidx;
5817da01
PH
2579 goto parse_done;
2580 }
2581
2582 if (!strcmp(ctx.argv[0], "--reverse")) {
2583 ctx.argv[0] = "--children";
2584 reverse = 1;
2585 }
6b61ec05 2586 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
5817da01
PH
2587 }
2588parse_done:
3d1aa566
JH
2589 no_whole_file_rename = !DIFF_OPT_TST(&revs.diffopt, FOLLOW_RENAMES);
2590 DIFF_OPT_CLR(&revs.diffopt, FOLLOW_RENAMES);
5817da01
PH
2591 argc = parse_options_end(&ctx);
2592
aba37f49
ECA
2593 if (incremental || (output_option & OUTPUT_PORCELAIN)) {
2594 if (show_progress > 0)
2595 die("--progress can't be used with --incremental or porcelain formats");
2596 show_progress = 0;
2597 } else if (show_progress < 0)
2598 show_progress = isatty(2);
2599
b31272f7
JH
2600 if (0 < abbrev)
2601 /* one more abbrev length is needed for the boundary commit */
2602 abbrev++;
84393bfd 2603
aa9ea77d 2604 if (revs_file && read_ancestry(revs_file))
d824cbba 2605 die_errno("reading graft file '%s' failed", revs_file);
aa9ea77d 2606
31653c1a 2607 if (cmd_is_annotate) {
7ceacdff 2608 output_option |= OUTPUT_ANNOTATE_COMPAT;
a5481a6c 2609 blame_date_mode.type = DATE_ISO8601;
31653c1a
EL
2610 } else {
2611 blame_date_mode = revs.date_mode;
2612 }
2613
2614 /* The maximum width used to show the dates */
a5481a6c 2615 switch (blame_date_mode.type) {
31653c1a
EL
2616 case DATE_RFC2822:
2617 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");
2618 break;
466fb674
BB
2619 case DATE_ISO8601_STRICT:
2620 blame_date_width = sizeof("2006-10-19T16:00:04-07:00");
2621 break;
31653c1a
EL
2622 case DATE_ISO8601:
2623 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");
2624 break;
2625 case DATE_RAW:
2626 blame_date_width = sizeof("1161298804 -0700");
2627 break;
642833db
JK
2628 case DATE_UNIX:
2629 blame_date_width = sizeof("1161298804");
2630 break;
31653c1a
EL
2631 case DATE_SHORT:
2632 blame_date_width = sizeof("2006-10-19");
2633 break;
2634 case DATE_RELATIVE:
dd75553b
JX
2635 /* TRANSLATORS: This string is used to tell us the maximum
2636 display width for a relative timestamp in "git blame"
2637 output. For C locale, "4 years, 11 months ago", which
2638 takes 22 places, is the longest among various forms of
2639 relative timestamps, but your language may need more or
2640 fewer display columns. */
2641 blame_date_width = utf8_strwidth(_("4 years, 11 months ago")) + 1; /* add the null */
2642 break;
31653c1a
EL
2643 case DATE_NORMAL:
2644 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");
2645 break;
aa1462cc
JK
2646 case DATE_STRFTIME:
2647 blame_date_width = strlen(show_date(0, 0, &blame_date_mode)) + 1; /* add the null */
2648 break;
31653c1a
EL
2649 }
2650 blame_date_width -= 1; /* strip the null */
7ceacdff 2651
b3123f98
JH
2652 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2653 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2654 PICKAXE_BLAME_COPY_HARDER);
2655
4a0fc95f
JH
2656 if (!blame_move_score)
2657 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2658 if (!blame_copy_score)
2659 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2660
1732a1fd
JH
2661 /*
2662 * We have collected options unknown to us in argv[1..unk]
cee7f245 2663 * which are to be passed to revision machinery if we are
3dff5379 2664 * going to do the "bottom" processing.
cee7f245
JH
2665 *
2666 * The remaining are:
2667 *
22e5e58a 2668 * (1) if dashdash_pos != 0, it is either
3f8d5204
PH
2669 * "blame [revisions] -- <path>" or
2670 * "blame -- <path> <rev>"
cee7f245 2671 *
22e5e58a 2672 * (2) otherwise, it is one of the two:
3f8d5204
PH
2673 * "blame [revisions] <path>"
2674 * "blame <path> <rev>"
cee7f245 2675 *
3f8d5204
PH
2676 * Note that we must strip out <path> from the arguments: we do not
2677 * want the path pruning but we may want "bottom" processing.
cee7f245 2678 */
3f8d5204
PH
2679 if (dashdash_pos) {
2680 switch (argc - dashdash_pos - 1) {
2681 case 2: /* (1b) */
2682 if (argc != 4)
5817da01 2683 usage_with_options(blame_opt_usage, options);
3f8d5204
PH
2684 /* reorder for the new way: <rev> -- <path> */
2685 argv[1] = argv[3];
2686 argv[3] = argv[2];
2687 argv[2] = "--";
2688 /* FALLTHROUGH */
2689 case 1: /* (1a) */
2690 path = add_prefix(prefix, argv[--argc]);
2691 argv[argc] = NULL;
2692 break;
2693 default:
2694 usage_with_options(blame_opt_usage, options);
cee7f245 2695 }
3f8d5204
PH
2696 } else {
2697 if (argc < 2)
5817da01 2698 usage_with_options(blame_opt_usage, options);
3f8d5204 2699 path = add_prefix(prefix, argv[argc - 1]);
dbe44faa 2700 if (argc == 3 && !file_exists(path)) { /* (2b) */
3f8d5204
PH
2701 path = add_prefix(prefix, argv[1]);
2702 argv[1] = argv[2];
cee7f245 2703 }
3f8d5204 2704 argv[argc - 1] = "--";
cee7f245 2705
3f8d5204 2706 setup_work_tree();
dbe44faa 2707 if (!file_exists(path))
d824cbba 2708 die_errno("cannot stat path '%s'", path);
cee7f245
JH
2709 }
2710
8b3dce56 2711 revs.disable_stdin = 1;
3f8d5204 2712 setup_revisions(argc, argv, &revs, NULL);
cee7f245
JH
2713 memset(&sb, 0, sizeof(sb));
2714
85af7929 2715 sb.revs = &revs;
7e6ac6e4 2716 if (!reverse) {
85af7929 2717 final_commit_name = prepare_final(&sb);
7e6ac6e4
DK
2718 sb.commits.compare = compare_commits_by_commit_date;
2719 }
85af7929 2720 else if (contents_from)
95261974 2721 die("--contents and --reverse do not blend well.");
7e6ac6e4 2722 else {
85af7929 2723 final_commit_name = prepare_initial(&sb);
7e6ac6e4 2724 sb.commits.compare = compare_commits_by_reverse_commit_date;
700fd28e
MK
2725 if (revs.first_parent_only)
2726 revs.children.name = NULL;
7e6ac6e4 2727 }
cee7f245
JH
2728
2729 if (!sb.final) {
1732a1fd
JH
2730 /*
2731 * "--not A B -- path" without anything positive;
1cfe7733
JH
2732 * do not default to HEAD, but use the working tree
2733 * or "--contents".
1732a1fd 2734 */
1981820b 2735 setup_work_tree();
3b8a12e8
AB
2736 sb.final = fake_working_tree_commit(&sb.revs->diffopt,
2737 path, contents_from);
1cfe7733 2738 add_pending_object(&revs, &(sb.final->object), ":");
cee7f245 2739 }
1cfe7733
JH
2740 else if (contents_from)
2741 die("Cannot use --contents with final commit object name");
cee7f245 2742
700fd28e 2743 if (reverse && revs.first_parent_only) {
7cb5f7c4
JK
2744 final_commit = find_single_final(sb.revs, NULL);
2745 if (!final_commit)
700fd28e 2746 die("--reverse and --first-parent together require specified latest commit");
700fd28e
MK
2747 }
2748
1732a1fd
JH
2749 /*
2750 * If we have bottom, this will mark the ancestors of the
cee7f245
JH
2751 * bottom commits we would reach while traversing as
2752 * uninteresting.
2753 */
3d51e1b5 2754 if (prepare_revision_walk(&revs))
20108742 2755 die(_("revision walk setup failed"));
cee7f245 2756
700fd28e
MK
2757 if (reverse && revs.first_parent_only) {
2758 struct commit *c = final_commit;
2759
2760 sb.revs->children.name = "children";
2761 while (c->parents &&
f2fd0760 2762 oidcmp(&c->object.oid, &sb.final->object.oid)) {
700fd28e
MK
2763 struct commit_list *l = xcalloc(1, sizeof(*l));
2764
2765 l->item = c;
2766 if (add_decoration(&sb.revs->children,
2767 &c->parents->item->object, l))
2768 die("BUG: not unique item in first-parent chain");
2769 c = c->parents->item;
2770 }
2771
f2fd0760 2772 if (oidcmp(&c->object.oid, &sb.final->object.oid))
700fd28e
MK
2773 die("--reverse --first-parent together require range along first-parent chain");
2774 }
2775
f2fd0760 2776 if (is_null_oid(&sb.final->object.oid)) {
1cfe7733 2777 o = sb.final->util;
5c0b13f8 2778 sb.final_buf = xmemdupz(o->file.ptr, o->file.size);
1cfe7733
JH
2779 sb.final_buf_size = o->file.size;
2780 }
2781 else {
2782 o = get_origin(&sb, sb.final, path);
90064710 2783 if (fill_blob_sha1_and_mode(o))
1cfe7733 2784 die("no such path %s in %s", path, final_commit_name);
cee7f245 2785
3b8a12e8 2786 if (DIFF_OPT_TST(&sb.revs->diffopt, ALLOW_TEXTCONV) &&
e5450100 2787 textconv_object(path, o->mode, o->blob_sha1, 1, (char **) &sb.final_buf,
3b8a12e8
AB
2788 &sb.final_buf_size))
2789 ;
2790 else
2791 sb.final_buf = read_sha1_file(o->blob_sha1, &type,
2792 &sb.final_buf_size);
2793
ab43e495
JH
2794 if (!sb.final_buf)
2795 die("Cannot read blob %s for path %s",
2796 sha1_to_hex(o->blob_sha1),
2797 path);
1cfe7733 2798 }
c2e525d9 2799 num_read_blob++;
cee7f245
JH
2800 lno = prepare_lines(&sb);
2801
58dbfa2e 2802 if (lno && !range_list.nr)
aa59e14b 2803 string_list_append(&range_list, "1");
58dbfa2e 2804
52f4d126 2805 anchor = 1;
58dbfa2e
ES
2806 range_set_init(&ranges, range_list.nr);
2807 for (range_i = 0; range_i < range_list.nr; ++range_i) {
2808 long bottom, top;
2809 if (parse_range_arg(range_list.items[range_i].string,
52f4d126 2810 nth_line_cb, &sb, lno, anchor,
58dbfa2e
ES
2811 &bottom, &top, sb.path))
2812 usage(blame_usage);
2813 if (lno < top || ((lno || bottom) && lno < bottom))
2814 die("file %s has only %lu lines", path, lno);
2815 if (bottom < 1)
2816 bottom = 1;
2817 if (top < 1)
2818 top = lno;
2819 bottom--;
2820 range_set_append_unsafe(&ranges, bottom, top);
52f4d126 2821 anchor = top + 1;
58dbfa2e
ES
2822 }
2823 sort_and_merge_range_set(&ranges);
2824
2825 for (range_i = ranges.nr; range_i > 0; --range_i) {
2826 const struct range *r = &ranges.ranges[range_i - 1];
2827 long bottom = r->start;
2828 long top = r->end;
2829 struct blame_entry *next = ent;
2830 ent = xcalloc(1, sizeof(*ent));
2831 ent->lno = bottom;
2832 ent->num_lines = top - bottom;
2833 ent->suspect = o;
2834 ent->s_lno = bottom;
2835 ent->next = next;
58dbfa2e
ES
2836 origin_incref(o);
2837 }
7e6ac6e4
DK
2838
2839 o->suspects = ent;
2840 prio_queue_put(&sb.commits, o->commit);
2841
58dbfa2e
ES
2842 origin_decref(o);
2843
2844 range_set_release(&ranges);
2845 string_list_clear(&range_list, 0);
cee7f245 2846
7e6ac6e4 2847 sb.ent = NULL;
cee7f245
JH
2848 sb.path = path;
2849
d551a488 2850 read_mailmap(&mailmap, NULL);
f9567384 2851
aba37f49
ECA
2852 assign_blame(&sb, opt);
2853
b92565dc
MH
2854 if (!incremental)
2855 setup_pager();
2856
a46442f1
LF
2857 free(final_commit_name);
2858
717d1462
LT
2859 if (incremental)
2860 return 0;
2861
7e6ac6e4
DK
2862 sb.ent = blame_sort(sb.ent, compare_blame_final);
2863
cee7f245
JH
2864 coalesce(&sb);
2865
2866 if (!(output_option & OUTPUT_PORCELAIN))
2867 find_alignment(&sb, &output_option);
2868
2869 output(&sb, output_option);
2870 free((void *)sb.final_buf);
2871 for (ent = sb.ent; ent; ) {
2872 struct blame_entry *e = ent->next;
2873 free(ent);
2874 ent = e;
2875 }
c2e525d9 2876
870b39c1 2877 if (show_stats) {
c2e525d9
JH
2878 printf("num read blob: %d\n", num_read_blob);
2879 printf("num get patch: %d\n", num_get_patch);
2880 printf("num commits: %d\n", num_commits);
2881 }
cee7f245
JH
2882 return 0;
2883}