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