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