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