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