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