Merge branch 'for-junio' of git://source.winehq.org/~julliard/git/git
[git/git.git] / builtin-blame.c
CommitLineData
cee7f245
JH
1/*
2 * Pickaxe
3 *
4 * Copyright (c) 2006, Junio C Hamano
5 */
6
7#include "cache.h"
8#include "builtin.h"
9#include "blob.h"
10#include "commit.h"
11#include "tag.h"
12#include "tree-walk.h"
13#include "diff.h"
14#include "diffcore.h"
15#include "revision.h"
717d1462 16#include "quote.h"
cee7f245 17#include "xdiff-interface.h"
1cfe7733 18#include "cache-tree.h"
c455c87c 19#include "string-list.h"
f9567384 20#include "mailmap.h"
5817da01 21#include "parse-options.h"
ffaf9cc0 22#include "utf8.h"
cee7f245 23
588c038a 24static char blame_usage[] = "git blame [options] [rev-opts] [rev] [--] file";
5817da01
PH
25
26static const char *blame_opt_usage[] = {
27 blame_usage,
28 "",
76447d23 29 "[rev-opts] are documented in git-rev-list(1)",
5817da01
PH
30 NULL
31};
cee7f245
JH
32
33static int longest_file;
34static int longest_author;
35static int max_orig_digits;
36static int max_digits;
5ff62c30 37static int max_score_digits;
4c10a5ca 38static int show_root;
85af7929 39static int reverse;
4c10a5ca 40static int blank_boundary;
717d1462 41static int incremental;
b82871b3 42static int xdl_opts = XDF_NEED_MINIMAL;
c455c87c 43static struct string_list mailmap;
cee7f245 44
54a4c617
JH
45#ifndef DEBUG
46#define DEBUG 0
47#endif
48
c2e525d9
JH
49/* stats */
50static int num_read_blob;
51static int num_get_patch;
52static int num_commits;
53
d24bba80 54#define PICKAXE_BLAME_MOVE 01
18abd745
JH
55#define PICKAXE_BLAME_COPY 02
56#define PICKAXE_BLAME_COPY_HARDER 04
c63777c0 57#define PICKAXE_BLAME_COPY_HARDEST 010
d24bba80 58
4a0fc95f
JH
59/*
60 * blame for a blame_entry with score lower than these thresholds
61 * is not passed to the parent using move/copy logic.
62 */
63static unsigned blame_move_score;
64static unsigned blame_copy_score;
65#define BLAME_DEFAULT_MOVE_SCORE 20
66#define BLAME_DEFAULT_COPY_SCORE 40
67
cee7f245
JH
68/* bits #0..7 in revision.h, #8..11 used for merge_bases() in commit.c */
69#define METAINFO_SHOWN (1u<<12)
70#define MORE_THAN_ONE_PATH (1u<<13)
71
72/*
54a4c617 73 * One blob in a commit that is being suspected
cee7f245
JH
74 */
75struct origin {
54a4c617 76 int refcnt;
cee7f245 77 struct commit *commit;
c2e525d9 78 mmfile_t file;
cee7f245
JH
79 unsigned char blob_sha1[20];
80 char path[FLEX_ARRAY];
81};
82
1732a1fd
JH
83/*
84 * Given an origin, prepare mmfile_t structure to be used by the
85 * diff machinery
86 */
f6c07d7d 87static void fill_origin_blob(struct origin *o, mmfile_t *file)
c2e525d9
JH
88{
89 if (!o->file.ptr) {
21666f1a 90 enum object_type type;
c2e525d9 91 num_read_blob++;
21666f1a 92 file->ptr = read_sha1_file(o->blob_sha1, &type,
c2e525d9 93 (unsigned long *)(&(file->size)));
ab43e495
JH
94 if (!file->ptr)
95 die("Cannot read blob %s for path %s",
96 sha1_to_hex(o->blob_sha1),
97 o->path);
c2e525d9
JH
98 o->file = *file;
99 }
100 else
101 *file = o->file;
c2e525d9
JH
102}
103
1732a1fd
JH
104/*
105 * Origin is refcounted and usually we keep the blob contents to be
106 * reused.
107 */
54a4c617
JH
108static inline struct origin *origin_incref(struct origin *o)
109{
110 if (o)
111 o->refcnt++;
112 return o;
113}
114
115static void origin_decref(struct origin *o)
116{
117 if (o && --o->refcnt <= 0) {
8e0f7003 118 free(o->file.ptr);
54a4c617
JH
119 free(o);
120 }
121}
122
7c3c7962
JH
123static void drop_origin_blob(struct origin *o)
124{
125 if (o->file.ptr) {
126 free(o->file.ptr);
127 o->file.ptr = NULL;
128 }
129}
130
1732a1fd
JH
131/*
132 * Each group of lines is described by a blame_entry; it can be split
133 * as we pass blame to the parents. They form a linked list in the
134 * scoreboard structure, sorted by the target line number.
135 */
cee7f245
JH
136struct blame_entry {
137 struct blame_entry *prev;
138 struct blame_entry *next;
139
140 /* the first line of this group in the final image;
141 * internally all line numbers are 0 based.
142 */
143 int lno;
144
145 /* how many lines this group has */
146 int num_lines;
147
148 /* the commit that introduced this group into the final image */
149 struct origin *suspect;
150
151 /* true if the suspect is truly guilty; false while we have not
152 * checked if the group came from one of its parents.
153 */
154 char guilty;
155
eb46328e
AG
156 /* true if the entry has been scanned for copies in the current parent
157 */
158 char scanned;
159
cee7f245
JH
160 /* the line number of the first line of this group in the
161 * suspect's file; internally all line numbers are 0 based.
162 */
163 int s_lno;
5ff62c30
JH
164
165 /* how significant this entry is -- cached to avoid
1732a1fd 166 * scanning the lines over and over.
5ff62c30
JH
167 */
168 unsigned score;
cee7f245
JH
169};
170
1732a1fd
JH
171/*
172 * The current state of the blame assignment.
173 */
cee7f245
JH
174struct scoreboard {
175 /* the final commit (i.e. where we started digging from) */
176 struct commit *final;
85af7929 177 struct rev_info *revs;
cee7f245
JH
178 const char *path;
179
1732a1fd
JH
180 /*
181 * The contents in the final image.
182 * Used by many functions to obtain contents of the nth line,
183 * indexed with scoreboard.lineno[blame_entry.lno].
cee7f245
JH
184 */
185 const char *final_buf;
186 unsigned long final_buf_size;
187
188 /* linked list of blames */
189 struct blame_entry *ent;
190
612702e8 191 /* look-up a line in the final buffer */
cee7f245
JH
192 int num_lines;
193 int *lineno;
194};
195
171dccd5 196static inline int same_suspect(struct origin *a, struct origin *b)
46014766 197{
171dccd5 198 if (a == b)
57584d9e 199 return 1;
171dccd5
JH
200 if (a->commit != b->commit)
201 return 0;
202 return !strcmp(a->path, b->path);
46014766
JH
203}
204
54a4c617
JH
205static void sanity_check_refcnt(struct scoreboard *);
206
1732a1fd
JH
207/*
208 * If two blame entries that are next to each other came from
209 * contiguous lines in the same origin (i.e. <commit, path> pair),
210 * merge them together.
211 */
cee7f245
JH
212static void coalesce(struct scoreboard *sb)
213{
214 struct blame_entry *ent, *next;
215
216 for (ent = sb->ent; ent && (next = ent->next); ent = next) {
171dccd5 217 if (same_suspect(ent->suspect, next->suspect) &&
cee7f245
JH
218 ent->guilty == next->guilty &&
219 ent->s_lno + ent->num_lines == next->s_lno) {
220 ent->num_lines += next->num_lines;
221 ent->next = next->next;
222 if (ent->next)
223 ent->next->prev = ent;
54a4c617 224 origin_decref(next->suspect);
cee7f245 225 free(next);
46014766 226 ent->score = 0;
cee7f245
JH
227 next = ent; /* again */
228 }
229 }
54a4c617
JH
230
231 if (DEBUG) /* sanity */
232 sanity_check_refcnt(sb);
cee7f245
JH
233}
234
1732a1fd
JH
235/*
236 * Given a commit and a path in it, create a new origin structure.
237 * The callers that add blame to the scoreboard should use
238 * get_origin() to obtain shared, refcounted copy instead of calling
239 * this function directly.
240 */
854b97f6
JH
241static struct origin *make_origin(struct commit *commit, const char *path)
242{
243 struct origin *o;
244 o = xcalloc(1, sizeof(*o) + strlen(path) + 1);
245 o->commit = commit;
246 o->refcnt = 1;
247 strcpy(o->path, path);
248 return o;
249}
250
1732a1fd
JH
251/*
252 * Locate an existing origin or create a new one.
253 */
f6c0e191
JH
254static struct origin *get_origin(struct scoreboard *sb,
255 struct commit *commit,
256 const char *path)
cee7f245 257{
f6c0e191 258 struct blame_entry *e;
cee7f245 259
f6c0e191
JH
260 for (e = sb->ent; e; e = e->next) {
261 if (e->suspect->commit == commit &&
262 !strcmp(e->suspect->path, path))
54a4c617 263 return origin_incref(e->suspect);
cee7f245 264 }
854b97f6 265 return make_origin(commit, path);
cee7f245
JH
266}
267
1732a1fd
JH
268/*
269 * Fill the blob_sha1 field of an origin if it hasn't, so that later
270 * call to fill_origin_blob() can use it to locate the data. blob_sha1
271 * for an origin is also used to pass the blame for the entire file to
272 * the parent to detect the case where a child's blob is identical to
273 * that of its parent's.
274 */
f6c0e191
JH
275static int fill_blob_sha1(struct origin *origin)
276{
277 unsigned mode;
f6c0e191
JH
278
279 if (!is_null_sha1(origin->blob_sha1))
280 return 0;
281 if (get_tree_entry(origin->commit->object.sha1,
282 origin->path,
283 origin->blob_sha1, &mode))
284 goto error_out;
21666f1a 285 if (sha1_object_info(origin->blob_sha1, NULL) != OBJ_BLOB)
f6c0e191
JH
286 goto error_out;
287 return 0;
288 error_out:
289 hashclr(origin->blob_sha1);
290 return -1;
291}
292
1732a1fd
JH
293/*
294 * We have an origin -- check if the same path exists in the
295 * parent and return an origin structure to represent it.
296 */
f6c0e191 297static struct origin *find_origin(struct scoreboard *sb,
cee7f245
JH
298 struct commit *parent,
299 struct origin *origin)
300{
301 struct origin *porigin = NULL;
302 struct diff_options diff_opts;
f6c0e191
JH
303 const char *paths[2];
304
0d981c67 305 if (parent->util) {
1732a1fd
JH
306 /*
307 * Each commit object can cache one origin in that
308 * commit. This is a freestanding copy of origin and
309 * not refcounted.
854b97f6 310 */
0d981c67 311 struct origin *cached = parent->util;
854b97f6 312 if (!strcmp(cached->path, origin->path)) {
1732a1fd
JH
313 /*
314 * The same path between origin and its parent
315 * without renaming -- the most common case.
316 */
854b97f6 317 porigin = get_origin(sb, parent, cached->path);
1732a1fd
JH
318
319 /*
320 * If the origin was newly created (i.e. get_origin
321 * would call make_origin if none is found in the
322 * scoreboard), it does not know the blob_sha1,
323 * so copy it. Otherwise porigin was in the
324 * scoreboard and already knows blob_sha1.
325 */
854b97f6
JH
326 if (porigin->refcnt == 1)
327 hashcpy(porigin->blob_sha1, cached->blob_sha1);
328 return porigin;
329 }
330 /* otherwise it was not very useful; free it */
331 free(parent->util);
332 parent->util = NULL;
0d981c67
JH
333 }
334
f6c0e191
JH
335 /* See if the origin->path is different between parent
336 * and origin first. Most of the time they are the
337 * same and diff-tree is fairly efficient about this.
338 */
339 diff_setup(&diff_opts);
8f67f8ae 340 DIFF_OPT_SET(&diff_opts, RECURSIVE);
f6c0e191
JH
341 diff_opts.detect_rename = 0;
342 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
343 paths[0] = origin->path;
344 paths[1] = NULL;
345
346 diff_tree_setup_paths(paths, &diff_opts);
347 if (diff_setup_done(&diff_opts) < 0)
348 die("diff-setup");
1cfe7733
JH
349
350 if (is_null_sha1(origin->commit->object.sha1))
351 do_diff_cache(parent->tree->object.sha1, &diff_opts);
352 else
353 diff_tree_sha1(parent->tree->object.sha1,
354 origin->commit->tree->object.sha1,
355 "", &diff_opts);
f6c0e191
JH
356 diffcore_std(&diff_opts);
357
358 /* It is either one entry that says "modified", or "created",
359 * or nothing.
360 */
361 if (!diff_queued_diff.nr) {
362 /* The path is the same as parent */
363 porigin = get_origin(sb, parent, origin->path);
364 hashcpy(porigin->blob_sha1, origin->blob_sha1);
365 }
366 else if (diff_queued_diff.nr != 1)
acca687f 367 die("internal error in blame::find_origin");
f6c0e191
JH
368 else {
369 struct diff_filepair *p = diff_queued_diff.queue[0];
370 switch (p->status) {
371 default:
acca687f 372 die("internal error in blame::find_origin (%c)",
f6c0e191
JH
373 p->status);
374 case 'M':
375 porigin = get_origin(sb, parent, origin->path);
376 hashcpy(porigin->blob_sha1, p->one->sha1);
377 break;
378 case 'A':
379 case 'T':
380 /* Did not exist in parent, or type changed */
381 break;
382 }
383 }
384 diff_flush(&diff_opts);
03b69c76 385 diff_tree_release_paths(&diff_opts);
0d981c67 386 if (porigin) {
1732a1fd
JH
387 /*
388 * Create a freestanding copy that is not part of
389 * the refcounted origin found in the scoreboard, and
390 * cache it in the commit.
391 */
854b97f6 392 struct origin *cached;
1732a1fd 393
854b97f6
JH
394 cached = make_origin(porigin->commit, porigin->path);
395 hashcpy(cached->blob_sha1, porigin->blob_sha1);
396 parent->util = cached;
0d981c67 397 }
f69e743d
JH
398 return porigin;
399}
f6c0e191 400
1732a1fd
JH
401/*
402 * We have an origin -- find the path that corresponds to it in its
403 * parent and return an origin structure to represent it.
404 */
f69e743d
JH
405static struct origin *find_rename(struct scoreboard *sb,
406 struct commit *parent,
407 struct origin *origin)
408{
409 struct origin *porigin = NULL;
410 struct diff_options diff_opts;
411 int i;
412 const char *paths[2];
cee7f245
JH
413
414 diff_setup(&diff_opts);
8f67f8ae 415 DIFF_OPT_SET(&diff_opts, RECURSIVE);
cee7f245
JH
416 diff_opts.detect_rename = DIFF_DETECT_RENAME;
417 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
2f3f8b21 418 diff_opts.single_follow = origin->path;
cee7f245
JH
419 paths[0] = NULL;
420 diff_tree_setup_paths(paths, &diff_opts);
421 if (diff_setup_done(&diff_opts) < 0)
422 die("diff-setup");
1cfe7733
JH
423
424 if (is_null_sha1(origin->commit->object.sha1))
425 do_diff_cache(parent->tree->object.sha1, &diff_opts);
426 else
427 diff_tree_sha1(parent->tree->object.sha1,
428 origin->commit->tree->object.sha1,
429 "", &diff_opts);
cee7f245
JH
430 diffcore_std(&diff_opts);
431
432 for (i = 0; i < diff_queued_diff.nr; i++) {
433 struct diff_filepair *p = diff_queued_diff.queue[i];
612702e8 434 if ((p->status == 'R' || p->status == 'C') &&
f6c0e191
JH
435 !strcmp(p->two->path, origin->path)) {
436 porigin = get_origin(sb, parent, p->one->path);
437 hashcpy(porigin->blob_sha1, p->one->sha1);
cee7f245
JH
438 break;
439 }
440 }
441 diff_flush(&diff_opts);
03b69c76 442 diff_tree_release_paths(&diff_opts);
cee7f245
JH
443 return porigin;
444}
445
1732a1fd 446/*
3dff5379 447 * Link in a new blame entry to the scoreboard. Entries that cover the
1732a1fd
JH
448 * same line range have been removed from the scoreboard previously.
449 */
cee7f245
JH
450static void add_blame_entry(struct scoreboard *sb, struct blame_entry *e)
451{
452 struct blame_entry *ent, *prev = NULL;
453
54a4c617
JH
454 origin_incref(e->suspect);
455
cee7f245
JH
456 for (ent = sb->ent; ent && ent->lno < e->lno; ent = ent->next)
457 prev = ent;
458
459 /* prev, if not NULL, is the last one that is below e */
460 e->prev = prev;
461 if (prev) {
462 e->next = prev->next;
463 prev->next = e;
464 }
465 else {
466 e->next = sb->ent;
467 sb->ent = e;
468 }
469 if (e->next)
470 e->next->prev = e;
471}
472
1732a1fd
JH
473/*
474 * src typically is on-stack; we want to copy the information in it to
790296fd 475 * a malloced blame_entry that is already on the linked list of the
1732a1fd
JH
476 * scoreboard. The origin of dst loses a refcnt while the origin of src
477 * gains one.
478 */
cee7f245
JH
479static void dup_entry(struct blame_entry *dst, struct blame_entry *src)
480{
481 struct blame_entry *p, *n;
54a4c617 482
cee7f245
JH
483 p = dst->prev;
484 n = dst->next;
54a4c617
JH
485 origin_incref(src->suspect);
486 origin_decref(dst->suspect);
cee7f245
JH
487 memcpy(dst, src, sizeof(*src));
488 dst->prev = p;
489 dst->next = n;
5ff62c30 490 dst->score = 0;
cee7f245
JH
491}
492
493static const char *nth_line(struct scoreboard *sb, int lno)
494{
495 return sb->final_buf + sb->lineno[lno];
496}
497
1732a1fd
JH
498/*
499 * It is known that lines between tlno to same came from parent, and e
500 * has an overlap with that range. it also is known that parent's
501 * line plno corresponds to e's line tlno.
502 *
503 * <---- e ----->
504 * <------>
505 * <------------>
506 * <------------>
507 * <------------------>
508 *
509 * Split e into potentially three parts; before this chunk, the chunk
510 * to be blamed for the parent, and after that portion.
511 */
54a4c617 512static void split_overlap(struct blame_entry *split,
cee7f245
JH
513 struct blame_entry *e,
514 int tlno, int plno, int same,
515 struct origin *parent)
516{
cee7f245
JH
517 int chunk_end_lno;
518 memset(split, 0, sizeof(struct blame_entry [3]));
519
520 if (e->s_lno < tlno) {
521 /* there is a pre-chunk part not blamed on parent */
54a4c617 522 split[0].suspect = origin_incref(e->suspect);
cee7f245
JH
523 split[0].lno = e->lno;
524 split[0].s_lno = e->s_lno;
525 split[0].num_lines = tlno - e->s_lno;
526 split[1].lno = e->lno + tlno - e->s_lno;
527 split[1].s_lno = plno;
528 }
529 else {
530 split[1].lno = e->lno;
531 split[1].s_lno = plno + (e->s_lno - tlno);
532 }
533
534 if (same < e->s_lno + e->num_lines) {
535 /* there is a post-chunk part not blamed on parent */
54a4c617 536 split[2].suspect = origin_incref(e->suspect);
cee7f245
JH
537 split[2].lno = e->lno + (same - e->s_lno);
538 split[2].s_lno = e->s_lno + (same - e->s_lno);
539 split[2].num_lines = e->s_lno + e->num_lines - same;
540 chunk_end_lno = split[2].lno;
541 }
542 else
543 chunk_end_lno = e->lno + e->num_lines;
544 split[1].num_lines = chunk_end_lno - split[1].lno;
545
1732a1fd
JH
546 /*
547 * if it turns out there is nothing to blame the parent for,
548 * forget about the splitting. !split[1].suspect signals this.
549 */
cee7f245
JH
550 if (split[1].num_lines < 1)
551 return;
54a4c617 552 split[1].suspect = origin_incref(parent);
cee7f245
JH
553}
554
1732a1fd
JH
555/*
556 * split_overlap() divided an existing blame e into up to three parts
557 * in split. Adjust the linked list of blames in the scoreboard to
558 * reflect the split.
559 */
cee7f245 560static void split_blame(struct scoreboard *sb,
54a4c617 561 struct blame_entry *split,
cee7f245
JH
562 struct blame_entry *e)
563{
564 struct blame_entry *new_entry;
565
566 if (split[0].suspect && split[2].suspect) {
1732a1fd 567 /* The first part (reuse storage for the existing entry e) */
cee7f245
JH
568 dup_entry(e, &split[0]);
569
1732a1fd 570 /* The last part -- me */
cee7f245
JH
571 new_entry = xmalloc(sizeof(*new_entry));
572 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
573 add_blame_entry(sb, new_entry);
574
1732a1fd 575 /* ... and the middle part -- parent */
cee7f245
JH
576 new_entry = xmalloc(sizeof(*new_entry));
577 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
578 add_blame_entry(sb, new_entry);
579 }
580 else if (!split[0].suspect && !split[2].suspect)
1732a1fd
JH
581 /*
582 * The parent covers the entire area; reuse storage for
583 * e and replace it with the parent.
584 */
cee7f245
JH
585 dup_entry(e, &split[1]);
586 else if (split[0].suspect) {
1732a1fd 587 /* me and then parent */
cee7f245
JH
588 dup_entry(e, &split[0]);
589
590 new_entry = xmalloc(sizeof(*new_entry));
591 memcpy(new_entry, &(split[1]), sizeof(struct blame_entry));
592 add_blame_entry(sb, new_entry);
593 }
594 else {
1732a1fd 595 /* parent and then me */
cee7f245
JH
596 dup_entry(e, &split[1]);
597
598 new_entry = xmalloc(sizeof(*new_entry));
599 memcpy(new_entry, &(split[2]), sizeof(struct blame_entry));
600 add_blame_entry(sb, new_entry);
601 }
602
54a4c617 603 if (DEBUG) { /* sanity */
cee7f245 604 struct blame_entry *ent;
612702e8 605 int lno = sb->ent->lno, corrupt = 0;
cee7f245
JH
606
607 for (ent = sb->ent; ent; ent = ent->next) {
608 if (lno != ent->lno)
609 corrupt = 1;
610 if (ent->s_lno < 0)
611 corrupt = 1;
612 lno += ent->num_lines;
613 }
614 if (corrupt) {
612702e8 615 lno = sb->ent->lno;
cee7f245
JH
616 for (ent = sb->ent; ent; ent = ent->next) {
617 printf("L %8d l %8d n %8d\n",
618 lno, ent->lno, ent->num_lines);
619 lno = ent->lno + ent->num_lines;
620 }
621 die("oops");
622 }
623 }
624}
625
1732a1fd
JH
626/*
627 * After splitting the blame, the origins used by the
628 * on-stack blame_entry should lose one refcnt each.
629 */
54a4c617
JH
630static void decref_split(struct blame_entry *split)
631{
632 int i;
633
634 for (i = 0; i < 3; i++)
635 origin_decref(split[i].suspect);
636}
637
1732a1fd
JH
638/*
639 * Helper for blame_chunk(). blame_entry e is known to overlap with
640 * the patch hunk; split it and pass blame to the parent.
641 */
cee7f245
JH
642static void blame_overlap(struct scoreboard *sb, struct blame_entry *e,
643 int tlno, int plno, int same,
644 struct origin *parent)
645{
646 struct blame_entry split[3];
647
648 split_overlap(split, e, tlno, plno, same, parent);
54a4c617
JH
649 if (split[1].suspect)
650 split_blame(sb, split, e);
651 decref_split(split);
cee7f245
JH
652}
653
1732a1fd
JH
654/*
655 * Find the line number of the last line the target is suspected for.
656 */
cee7f245
JH
657static int find_last_in_target(struct scoreboard *sb, struct origin *target)
658{
659 struct blame_entry *e;
660 int last_in_target = -1;
661
662 for (e = sb->ent; e; e = e->next) {
171dccd5 663 if (e->guilty || !same_suspect(e->suspect, target))
cee7f245
JH
664 continue;
665 if (last_in_target < e->s_lno + e->num_lines)
666 last_in_target = e->s_lno + e->num_lines;
667 }
668 return last_in_target;
669}
670
1732a1fd
JH
671/*
672 * Process one hunk from the patch between the current suspect for
673 * blame_entry e and its parent. Find and split the overlap, and
674 * pass blame to the overlapping part to the parent.
675 */
cee7f245
JH
676static void blame_chunk(struct scoreboard *sb,
677 int tlno, int plno, int same,
678 struct origin *target, struct origin *parent)
679{
612702e8 680 struct blame_entry *e;
cee7f245 681
612702e8 682 for (e = sb->ent; e; e = e->next) {
171dccd5 683 if (e->guilty || !same_suspect(e->suspect, target))
cee7f245
JH
684 continue;
685 if (same <= e->s_lno)
686 continue;
687 if (tlno < e->s_lno + e->num_lines)
688 blame_overlap(sb, e, tlno, plno, same, parent);
689 }
690}
691
cdcab133
RS
692struct blame_chunk_cb_data {
693 struct scoreboard *sb;
694 struct origin *target;
695 struct origin *parent;
696 long plno;
697 long tlno;
698};
699
700static void blame_chunk_cb(void *data, long same, long p_next, long t_next)
701{
702 struct blame_chunk_cb_data *d = data;
703 blame_chunk(d->sb, d->tlno, d->plno, same, d->target, d->parent);
704 d->plno = p_next;
705 d->tlno = t_next;
706}
707
1732a1fd
JH
708/*
709 * We are looking at the origin 'target' and aiming to pass blame
710 * for the lines it is suspected to its parent. Run diff to find
711 * which lines came from parent and pass blame for them.
712 */
cee7f245
JH
713static int pass_blame_to_parent(struct scoreboard *sb,
714 struct origin *target,
715 struct origin *parent)
716{
cdcab133 717 int last_in_target;
7c4ed8c8 718 mmfile_t file_p, file_o;
cdcab133
RS
719 struct blame_chunk_cb_data d = { sb, target, parent, 0, 0 };
720 xpparam_t xpp;
721 xdemitconf_t xecfg;
cee7f245
JH
722
723 last_in_target = find_last_in_target(sb, target);
724 if (last_in_target < 0)
725 return 1; /* nothing remains for this target */
726
7c4ed8c8
RS
727 fill_origin_blob(parent, &file_p);
728 fill_origin_blob(target, &file_o);
7c4ed8c8 729 num_get_patch++;
cee7f245 730
cdcab133
RS
731 memset(&xpp, 0, sizeof(xpp));
732 xpp.flags = xdl_opts;
733 memset(&xecfg, 0, sizeof(xecfg));
734 xecfg.ctxlen = 0;
735 xdi_diff_hunks(&file_p, &file_o, blame_chunk_cb, &d, &xpp, &xecfg);
1732a1fd 736 /* The rest (i.e. anything after tlno) are the same as the parent */
cdcab133 737 blame_chunk(sb, d.tlno, d.plno, last_in_target, target, parent);
cee7f245 738
cee7f245
JH
739 return 0;
740}
741
1732a1fd
JH
742/*
743 * The lines in blame_entry after splitting blames many times can become
744 * very small and trivial, and at some point it becomes pointless to
745 * blame the parents. E.g. "\t\t}\n\t}\n\n" appears everywhere in any
746 * ordinary C program, and it is not worth to say it was copied from
747 * totally unrelated file in the parent.
748 *
749 * Compute how trivial the lines in the blame_entry are.
750 */
5ff62c30
JH
751static unsigned ent_score(struct scoreboard *sb, struct blame_entry *e)
752{
753 unsigned score;
754 const char *cp, *ep;
755
756 if (e->score)
757 return e->score;
758
612702e8 759 score = 1;
5ff62c30
JH
760 cp = nth_line(sb, e->lno);
761 ep = nth_line(sb, e->lno + e->num_lines);
762 while (cp < ep) {
763 unsigned ch = *((unsigned char *)cp);
764 if (isalnum(ch))
765 score++;
766 cp++;
767 }
768 e->score = score;
769 return score;
770}
771
1732a1fd
JH
772/*
773 * best_so_far[] and this[] are both a split of an existing blame_entry
774 * that passes blame to the parent. Maintain best_so_far the best split
775 * so far, by comparing this and best_so_far and copying this into
776 * bst_so_far as needed.
777 */
5ff62c30 778static void copy_split_if_better(struct scoreboard *sb,
54a4c617
JH
779 struct blame_entry *best_so_far,
780 struct blame_entry *this)
d24bba80 781{
54a4c617
JH
782 int i;
783
d24bba80
JH
784 if (!this[1].suspect)
785 return;
5ff62c30
JH
786 if (best_so_far[1].suspect) {
787 if (ent_score(sb, &this[1]) < ent_score(sb, &best_so_far[1]))
788 return;
789 }
54a4c617
JH
790
791 for (i = 0; i < 3; i++)
792 origin_incref(this[i].suspect);
793 decref_split(best_so_far);
d24bba80
JH
794 memcpy(best_so_far, this, sizeof(struct blame_entry [3]));
795}
796
dd166aa8
JH
797/*
798 * We are looking at a part of the final image represented by
799 * ent (tlno and same are offset by ent->s_lno).
800 * tlno is where we are looking at in the final image.
801 * up to (but not including) same match preimage.
802 * plno is where we are looking at in the preimage.
803 *
804 * <-------------- final image ---------------------->
805 * <------ent------>
806 * ^tlno ^same
807 * <---------preimage----->
808 * ^plno
809 *
810 * All line numbers are 0-based.
811 */
812static void handle_split(struct scoreboard *sb,
813 struct blame_entry *ent,
814 int tlno, int plno, int same,
815 struct origin *parent,
816 struct blame_entry *split)
817{
818 if (ent->num_lines <= tlno)
819 return;
820 if (tlno < same) {
821 struct blame_entry this[3];
822 tlno += ent->s_lno;
823 same += ent->s_lno;
824 split_overlap(this, ent, tlno, plno, same, parent);
825 copy_split_if_better(sb, split, this);
826 decref_split(this);
827 }
828}
829
cdcab133
RS
830struct handle_split_cb_data {
831 struct scoreboard *sb;
832 struct blame_entry *ent;
833 struct origin *parent;
834 struct blame_entry *split;
835 long plno;
836 long tlno;
837};
838
839static void handle_split_cb(void *data, long same, long p_next, long t_next)
840{
841 struct handle_split_cb_data *d = data;
842 handle_split(d->sb, d->ent, d->tlno, d->plno, same, d->parent, d->split);
843 d->plno = p_next;
844 d->tlno = t_next;
845}
846
1732a1fd
JH
847/*
848 * Find the lines from parent that are the same as ent so that
849 * we can pass blames to it. file_p has the blob contents for
850 * the parent.
851 */
d24bba80
JH
852static void find_copy_in_blob(struct scoreboard *sb,
853 struct blame_entry *ent,
854 struct origin *parent,
54a4c617 855 struct blame_entry *split,
d24bba80
JH
856 mmfile_t *file_p)
857{
858 const char *cp;
859 int cnt;
860 mmfile_t file_o;
cdcab133
RS
861 struct handle_split_cb_data d = { sb, ent, parent, split, 0, 0 };
862 xpparam_t xpp;
863 xdemitconf_t xecfg;
d24bba80 864
1732a1fd
JH
865 /*
866 * Prepare mmfile that contains only the lines in ent.
867 */
d24bba80
JH
868 cp = nth_line(sb, ent->lno);
869 file_o.ptr = (char*) cp;
870 cnt = ent->num_lines;
871
872 while (cnt && cp < sb->final_buf + sb->final_buf_size) {
873 if (*cp++ == '\n')
874 cnt--;
875 }
876 file_o.size = cp - file_o.ptr;
877
dd166aa8
JH
878 /*
879 * file_o is a part of final image we are annotating.
880 * file_p partially may match that image.
881 */
cdcab133
RS
882 memset(&xpp, 0, sizeof(xpp));
883 xpp.flags = xdl_opts;
884 memset(&xecfg, 0, sizeof(xecfg));
885 xecfg.ctxlen = 1;
d24bba80 886 memset(split, 0, sizeof(struct blame_entry [3]));
cdcab133 887 xdi_diff_hunks(file_p, &file_o, handle_split_cb, &d, &xpp, &xecfg);
dd166aa8 888 /* remainder, if any, all match the preimage */
cdcab133 889 handle_split(sb, ent, d.tlno, d.plno, ent->num_lines, parent, split);
d24bba80
JH
890}
891
1732a1fd
JH
892/*
893 * See if lines currently target is suspected for can be attributed to
894 * parent.
895 */
d24bba80
JH
896static int find_move_in_parent(struct scoreboard *sb,
897 struct origin *target,
898 struct origin *parent)
899{
650e2f67 900 int last_in_target, made_progress;
46014766 901 struct blame_entry *e, split[3];
d24bba80 902 mmfile_t file_p;
d24bba80
JH
903
904 last_in_target = find_last_in_target(sb, target);
905 if (last_in_target < 0)
906 return 1; /* nothing remains for this target */
907
c2e525d9
JH
908 fill_origin_blob(parent, &file_p);
909 if (!file_p.ptr)
d24bba80 910 return 0;
d24bba80 911
650e2f67
JH
912 made_progress = 1;
913 while (made_progress) {
914 made_progress = 0;
915 for (e = sb->ent; e; e = e->next) {
1617fe98
AG
916 if (e->guilty || !same_suspect(e->suspect, target) ||
917 ent_score(sb, e) < blame_move_score)
650e2f67
JH
918 continue;
919 find_copy_in_blob(sb, e, parent, split, &file_p);
920 if (split[1].suspect &&
921 blame_move_score < ent_score(sb, &split[1])) {
922 split_blame(sb, split, e);
923 made_progress = 1;
924 }
925 decref_split(split);
926 }
d24bba80 927 }
d24bba80
JH
928 return 0;
929}
930
33494784
JH
931struct blame_list {
932 struct blame_entry *ent;
933 struct blame_entry split[3];
934};
935
1732a1fd
JH
936/*
937 * Count the number of entries the target is suspected for,
938 * and prepare a list of entry and the best split.
939 */
33494784
JH
940static struct blame_list *setup_blame_list(struct scoreboard *sb,
941 struct origin *target,
1617fe98 942 int min_score,
33494784
JH
943 int *num_ents_p)
944{
945 struct blame_entry *e;
946 int num_ents, i;
947 struct blame_list *blame_list = NULL;
948
33494784 949 for (e = sb->ent, num_ents = 0; e; e = e->next)
1617fe98
AG
950 if (!e->scanned && !e->guilty &&
951 same_suspect(e->suspect, target) &&
952 min_score < ent_score(sb, e))
33494784
JH
953 num_ents++;
954 if (num_ents) {
955 blame_list = xcalloc(num_ents, sizeof(struct blame_list));
956 for (e = sb->ent, i = 0; e; e = e->next)
1617fe98
AG
957 if (!e->scanned && !e->guilty &&
958 same_suspect(e->suspect, target) &&
959 min_score < ent_score(sb, e))
33494784
JH
960 blame_list[i++].ent = e;
961 }
962 *num_ents_p = num_ents;
963 return blame_list;
964}
965
eb46328e
AG
966/*
967 * Reset the scanned status on all entries.
968 */
969static void reset_scanned_flag(struct scoreboard *sb)
970{
971 struct blame_entry *e;
972 for (e = sb->ent; e; e = e->next)
973 e->scanned = 0;
974}
975
1732a1fd
JH
976/*
977 * For lines target is suspected for, see if we can find code movement
978 * across file boundary from the parent commit. porigin is the path
979 * in the parent we already tried.
980 */
18abd745
JH
981static int find_copy_in_parent(struct scoreboard *sb,
982 struct origin *target,
983 struct commit *parent,
984 struct origin *porigin,
985 int opt)
986{
987 struct diff_options diff_opts;
988 const char *paths[1];
aec8fa1f 989 int i, j;
33494784
JH
990 int retval;
991 struct blame_list *blame_list;
aec8fa1f 992 int num_ents;
18abd745 993
1617fe98 994 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
33494784 995 if (!blame_list)
18abd745
JH
996 return 1; /* nothing remains for this target */
997
998 diff_setup(&diff_opts);
8f67f8ae 999 DIFF_OPT_SET(&diff_opts, RECURSIVE);
18abd745
JH
1000 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
1001
18abd745
JH
1002 paths[0] = NULL;
1003 diff_tree_setup_paths(paths, &diff_opts);
1004 if (diff_setup_done(&diff_opts) < 0)
1005 die("diff-setup");
33494784
JH
1006
1007 /* Try "find copies harder" on new path if requested;
1008 * we do not want to use diffcore_rename() actually to
1009 * match things up; find_copies_harder is set only to
1010 * force diff_tree_sha1() to feed all filepairs to diff_queue,
1011 * and this code needs to be after diff_setup_done(), which
1012 * usually makes find-copies-harder imply copy detection.
1013 */
c63777c0
JH
1014 if ((opt & PICKAXE_BLAME_COPY_HARDEST)
1015 || ((opt & PICKAXE_BLAME_COPY_HARDER)
1016 && (!porigin || strcmp(target->path, porigin->path))))
8f67f8ae 1017 DIFF_OPT_SET(&diff_opts, FIND_COPIES_HARDER);
33494784 1018
1cfe7733
JH
1019 if (is_null_sha1(target->commit->object.sha1))
1020 do_diff_cache(parent->tree->object.sha1, &diff_opts);
1021 else
1022 diff_tree_sha1(parent->tree->object.sha1,
1023 target->commit->tree->object.sha1,
1024 "", &diff_opts);
18abd745 1025
8f67f8ae 1026 if (!DIFF_OPT_TST(&diff_opts, FIND_COPIES_HARDER))
33494784 1027 diffcore_std(&diff_opts);
18abd745 1028
33494784
JH
1029 retval = 0;
1030 while (1) {
1031 int made_progress = 0;
1032
1033 for (i = 0; i < diff_queued_diff.nr; i++) {
1034 struct diff_filepair *p = diff_queued_diff.queue[i];
1035 struct origin *norigin;
1036 mmfile_t file_p;
33494784
JH
1037 struct blame_entry this[3];
1038
1039 if (!DIFF_FILE_VALID(p->one))
1040 continue; /* does not exist in parent */
5209ac4d
AG
1041 if (S_ISGITLINK(p->one->mode))
1042 continue; /* ignore git links */
33494784
JH
1043 if (porigin && !strcmp(p->one->path, porigin->path))
1044 /* find_move already dealt with this path */
1045 continue;
1046
1047 norigin = get_origin(sb, parent, p->one->path);
1048 hashcpy(norigin->blob_sha1, p->one->sha1);
c2e525d9 1049 fill_origin_blob(norigin, &file_p);
33494784
JH
1050 if (!file_p.ptr)
1051 continue;
1052
1053 for (j = 0; j < num_ents; j++) {
1054 find_copy_in_blob(sb, blame_list[j].ent,
1055 norigin, this, &file_p);
1056 copy_split_if_better(sb, blame_list[j].split,
1057 this);
1058 decref_split(this);
1059 }
33494784
JH
1060 origin_decref(norigin);
1061 }
18abd745 1062
aec8fa1f 1063 for (j = 0; j < num_ents; j++) {
33494784
JH
1064 struct blame_entry *split = blame_list[j].split;
1065 if (split[1].suspect &&
1066 blame_copy_score < ent_score(sb, &split[1])) {
1067 split_blame(sb, split, blame_list[j].ent);
1068 made_progress = 1;
1069 }
eb46328e
AG
1070 else
1071 blame_list[j].ent->scanned = 1;
33494784 1072 decref_split(split);
18abd745 1073 }
33494784 1074 free(blame_list);
aec8fa1f 1075
33494784
JH
1076 if (!made_progress)
1077 break;
1617fe98 1078 blame_list = setup_blame_list(sb, target, blame_copy_score, &num_ents);
33494784
JH
1079 if (!blame_list) {
1080 retval = 1;
1081 break;
1082 }
18abd745 1083 }
eb46328e 1084 reset_scanned_flag(sb);
33494784 1085 diff_flush(&diff_opts);
03b69c76 1086 diff_tree_release_paths(&diff_opts);
33494784 1087 return retval;
18abd745
JH
1088}
1089
1732a1fd
JH
1090/*
1091 * The blobs of origin and porigin exactly match, so everything
c2e525d9
JH
1092 * origin is suspected for can be blamed on the parent.
1093 */
1094static void pass_whole_blame(struct scoreboard *sb,
1095 struct origin *origin, struct origin *porigin)
1096{
1097 struct blame_entry *e;
1098
1099 if (!porigin->file.ptr && origin->file.ptr) {
1100 /* Steal its file */
1101 porigin->file = origin->file;
1102 origin->file.ptr = NULL;
1103 }
1104 for (e = sb->ent; e; e = e->next) {
171dccd5 1105 if (!same_suspect(e->suspect, origin))
c2e525d9
JH
1106 continue;
1107 origin_incref(porigin);
1108 origin_decref(e->suspect);
1109 e->suspect = porigin;
1110 }
1111}
1112
69264f46
JH
1113/*
1114 * We pass blame from the current commit to its parents. We keep saying
1115 * "parent" (and "porigin"), but what we mean is to find scapegoat to
1116 * exonerate ourselves.
1117 */
85af7929 1118static struct commit_list *first_scapegoat(struct rev_info *revs, struct commit *commit)
69264f46 1119{
85af7929
JH
1120 if (!reverse)
1121 return commit->parents;
1122 return lookup_decoration(&revs->children, &commit->object);
69264f46
JH
1123}
1124
85af7929 1125static int num_scapegoats(struct rev_info *revs, struct commit *commit)
69264f46
JH
1126{
1127 int cnt;
85af7929 1128 struct commit_list *l = first_scapegoat(revs, commit);
69264f46
JH
1129 for (cnt = 0; l; l = l->next)
1130 cnt++;
1131 return cnt;
1132}
1133
1134#define MAXSG 16
cee7f245 1135
d24bba80 1136static void pass_blame(struct scoreboard *sb, struct origin *origin, int opt)
cee7f245 1137{
85af7929 1138 struct rev_info *revs = sb->revs;
69264f46 1139 int i, pass, num_sg;
cee7f245 1140 struct commit *commit = origin->commit;
69264f46
JH
1141 struct commit_list *sg;
1142 struct origin *sg_buf[MAXSG];
1143 struct origin *porigin, **sg_origin = sg_buf;
1144
85af7929 1145 num_sg = num_scapegoats(revs, commit);
69264f46
JH
1146 if (!num_sg)
1147 goto finish;
1148 else if (num_sg < ARRAY_SIZE(sg_buf))
1149 memset(sg_buf, 0, sizeof(sg_buf));
1150 else
1151 sg_origin = xcalloc(num_sg, sizeof(*sg_origin));
cee7f245 1152
69264f46
JH
1153 /*
1154 * The first pass looks for unrenamed path to optimize for
f69e743d
JH
1155 * common cases, then we look for renames in the second pass.
1156 */
1157 for (pass = 0; pass < 2; pass++) {
1158 struct origin *(*find)(struct scoreboard *,
1159 struct commit *, struct origin *);
1160 find = pass ? find_rename : find_origin;
1161
85af7929 1162 for (i = 0, sg = first_scapegoat(revs, commit);
69264f46
JH
1163 i < num_sg && sg;
1164 sg = sg->next, i++) {
1165 struct commit *p = sg->item;
0421d9f8 1166 int j, same;
f69e743d 1167
69264f46 1168 if (sg_origin[i])
f69e743d
JH
1169 continue;
1170 if (parse_commit(p))
1171 continue;
0d981c67 1172 porigin = find(sb, p, origin);
f69e743d
JH
1173 if (!porigin)
1174 continue;
1175 if (!hashcmp(porigin->blob_sha1, origin->blob_sha1)) {
c2e525d9 1176 pass_whole_blame(sb, origin, porigin);
f69e743d
JH
1177 origin_decref(porigin);
1178 goto finish;
1179 }
0421d9f8 1180 for (j = same = 0; j < i; j++)
69264f46
JH
1181 if (sg_origin[j] &&
1182 !hashcmp(sg_origin[j]->blob_sha1,
0421d9f8
JH
1183 porigin->blob_sha1)) {
1184 same = 1;
1185 break;
1186 }
1187 if (!same)
69264f46 1188 sg_origin[i] = porigin;
0421d9f8
JH
1189 else
1190 origin_decref(porigin);
cee7f245 1191 }
cee7f245
JH
1192 }
1193
c2e525d9 1194 num_commits++;
85af7929 1195 for (i = 0, sg = first_scapegoat(revs, commit);
69264f46
JH
1196 i < num_sg && sg;
1197 sg = sg->next, i++) {
1198 struct origin *porigin = sg_origin[i];
cee7f245
JH
1199 if (!porigin)
1200 continue;
1201 if (pass_blame_to_parent(sb, origin, porigin))
54a4c617 1202 goto finish;
cee7f245 1203 }
d24bba80
JH
1204
1205 /*
1732a1fd 1206 * Optionally find moves in parents' files.
d24bba80
JH
1207 */
1208 if (opt & PICKAXE_BLAME_MOVE)
85af7929 1209 for (i = 0, sg = first_scapegoat(revs, commit);
69264f46
JH
1210 i < num_sg && sg;
1211 sg = sg->next, i++) {
1212 struct origin *porigin = sg_origin[i];
d24bba80
JH
1213 if (!porigin)
1214 continue;
1215 if (find_move_in_parent(sb, origin, porigin))
54a4c617 1216 goto finish;
d24bba80
JH
1217 }
1218
18abd745 1219 /*
1732a1fd 1220 * Optionally find copies from parents' files.
18abd745
JH
1221 */
1222 if (opt & PICKAXE_BLAME_COPY)
85af7929 1223 for (i = 0, sg = first_scapegoat(revs, commit);
69264f46
JH
1224 i < num_sg && sg;
1225 sg = sg->next, i++) {
1226 struct origin *porigin = sg_origin[i];
1227 if (find_copy_in_parent(sb, origin, sg->item,
18abd745 1228 porigin, opt))
54a4c617 1229 goto finish;
18abd745 1230 }
54a4c617
JH
1231
1232 finish:
69264f46
JH
1233 for (i = 0; i < num_sg; i++) {
1234 if (sg_origin[i]) {
1235 drop_origin_blob(sg_origin[i]);
1236 origin_decref(sg_origin[i]);
7c3c7962
JH
1237 }
1238 }
1239 drop_origin_blob(origin);
69264f46
JH
1240 if (sg_buf != sg_origin)
1241 free(sg_origin);
cee7f245
JH
1242}
1243
1732a1fd
JH
1244/*
1245 * Information on commits, used for output.
1246 */
cee7f245
JH
1247struct commit_info
1248{
3a55602e
SP
1249 const char *author;
1250 const char *author_mail;
cee7f245 1251 unsigned long author_time;
3a55602e 1252 const char *author_tz;
cee7f245
JH
1253
1254 /* filled only when asked for details */
3a55602e
SP
1255 const char *committer;
1256 const char *committer_mail;
cee7f245 1257 unsigned long committer_time;
3a55602e 1258 const char *committer_tz;
cee7f245 1259
3a55602e 1260 const char *summary;
cee7f245
JH
1261};
1262
1732a1fd
JH
1263/*
1264 * Parse author/committer line in the commit object buffer
1265 */
cee7f245 1266static void get_ac_line(const char *inbuf, const char *what,
d20d654f
MSO
1267 int person_len, char *person,
1268 int mail_len, char *mail,
3a55602e 1269 unsigned long *time, const char **tz)
cee7f245 1270{
f9567384 1271 int len, tzlen, maillen;
d20d654f 1272 char *tmp, *endp, *timepos, *mailpos;
cee7f245
JH
1273
1274 tmp = strstr(inbuf, what);
1275 if (!tmp)
1276 goto error_out;
1277 tmp += strlen(what);
1278 endp = strchr(tmp, '\n');
1279 if (!endp)
1280 len = strlen(tmp);
1281 else
1282 len = endp - tmp;
d20d654f 1283 if (person_len <= len) {
cee7f245
JH
1284 error_out:
1285 /* Ugh */
d20d654f
MSO
1286 *tz = "(unknown)";
1287 strcpy(mail, *tz);
cee7f245
JH
1288 *time = 0;
1289 return;
1290 }
1291 memcpy(person, tmp, len);
1292
1293 tmp = person;
1294 tmp += len;
1295 *tmp = 0;
1296 while (*tmp != ' ')
1297 tmp--;
1298 *tz = tmp+1;
f9567384 1299 tzlen = (person+len)-(tmp+1);
cee7f245
JH
1300
1301 *tmp = 0;
1302 while (*tmp != ' ')
1303 tmp--;
1304 *time = strtoul(tmp, NULL, 10);
f9567384 1305 timepos = tmp;
cee7f245
JH
1306
1307 *tmp = 0;
1308 while (*tmp != ' ')
1309 tmp--;
d20d654f 1310 mailpos = tmp + 1;
cee7f245 1311 *tmp = 0;
f9567384 1312 maillen = timepos - tmp;
d20d654f 1313 memcpy(mail, mailpos, maillen);
f9567384
JH
1314
1315 if (!mailmap.nr)
1316 return;
1317
1318 /*
1319 * mailmap expansion may make the name longer.
1320 * make room by pushing stuff down.
1321 */
d20d654f 1322 tmp = person + person_len - (tzlen + 1);
f9567384
JH
1323 memmove(tmp, *tz, tzlen);
1324 tmp[tzlen] = 0;
1325 *tz = tmp;
1326
f9567384 1327 /*
d20d654f 1328 * Now, convert both name and e-mail using mailmap
f9567384 1329 */
d20d654f
MSO
1330 if(map_user(&mailmap, mail+1, mail_len-1, person, tmp-person-1)) {
1331 /* Add a trailing '>' to email, since map_user returns plain emails
1332 Note: It already has '<', since we replace from mail+1 */
1333 mailpos = memchr(mail, '\0', mail_len);
1334 if (mailpos && mailpos-mail < mail_len - 1) {
1335 *mailpos = '>';
1336 *(mailpos+1) = '\0';
1337 }
1338 }
cee7f245
JH
1339}
1340
1341static void get_commit_info(struct commit *commit,
1342 struct commit_info *ret,
1343 int detailed)
1344{
1345 int len;
69cd8f63 1346 char *tmp, *endp, *reencoded, *message;
d20d654f
MSO
1347 static char author_name[1024];
1348 static char author_mail[1024];
1349 static char committer_name[1024];
1350 static char committer_mail[1024];
cee7f245
JH
1351 static char summary_buf[1024];
1352
1732a1fd
JH
1353 /*
1354 * We've operated without save_commit_buffer, so
612702e8
JH
1355 * we now need to populate them for output.
1356 */
1357 if (!commit->buffer) {
21666f1a 1358 enum object_type type;
612702e8
JH
1359 unsigned long size;
1360 commit->buffer =
21666f1a 1361 read_sha1_file(commit->object.sha1, &type, &size);
ab43e495
JH
1362 if (!commit->buffer)
1363 die("Cannot read commit %s",
1364 sha1_to_hex(commit->object.sha1));
612702e8 1365 }
69cd8f63
AG
1366 reencoded = reencode_commit_message(commit, NULL);
1367 message = reencoded ? reencoded : commit->buffer;
d20d654f
MSO
1368 ret->author = author_name;
1369 ret->author_mail = author_mail;
69cd8f63 1370 get_ac_line(message, "\nauthor ",
d20d654f
MSO
1371 sizeof(author_name), author_name,
1372 sizeof(author_mail), author_mail,
cee7f245
JH
1373 &ret->author_time, &ret->author_tz);
1374
69cd8f63
AG
1375 if (!detailed) {
1376 free(reencoded);
cee7f245 1377 return;
69cd8f63 1378 }
cee7f245 1379
d20d654f
MSO
1380 ret->committer = committer_name;
1381 ret->committer_mail = committer_mail;
69cd8f63 1382 get_ac_line(message, "\ncommitter ",
d20d654f
MSO
1383 sizeof(committer_name), committer_name,
1384 sizeof(committer_mail), committer_mail,
cee7f245
JH
1385 &ret->committer_time, &ret->committer_tz);
1386
1387 ret->summary = summary_buf;
69cd8f63 1388 tmp = strstr(message, "\n\n");
cee7f245
JH
1389 if (!tmp) {
1390 error_out:
1391 sprintf(summary_buf, "(%s)", sha1_to_hex(commit->object.sha1));
69cd8f63 1392 free(reencoded);
cee7f245
JH
1393 return;
1394 }
1395 tmp += 2;
1396 endp = strchr(tmp, '\n');
1397 if (!endp)
1cfe7733 1398 endp = tmp + strlen(tmp);
cee7f245 1399 len = endp - tmp;
1cfe7733 1400 if (len >= sizeof(summary_buf) || len == 0)
cee7f245
JH
1401 goto error_out;
1402 memcpy(summary_buf, tmp, len);
1403 summary_buf[len] = 0;
69cd8f63 1404 free(reencoded);
cee7f245
JH
1405}
1406
1732a1fd
JH
1407/*
1408 * To allow LF and other nonportable characters in pathnames,
1409 * they are c-style quoted as needed.
1410 */
46e5e69d
JH
1411static void write_filename_info(const char *path)
1412{
1413 printf("filename ");
663af342 1414 write_name_quoted(path, stdout, '\n');
46e5e69d
JH
1415}
1416
1732a1fd
JH
1417/*
1418 * The blame_entry is found to be guilty for the range. Mark it
1419 * as such, and show it in incremental output.
1420 */
717d1462
LT
1421static void found_guilty_entry(struct blame_entry *ent)
1422{
1423 if (ent->guilty)
1424 return;
1425 ent->guilty = 1;
1426 if (incremental) {
1427 struct origin *suspect = ent->suspect;
1428
1429 printf("%s %d %d %d\n",
1430 sha1_to_hex(suspect->commit->object.sha1),
1431 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
1432 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1433 struct commit_info ci;
1434 suspect->commit->object.flags |= METAINFO_SHOWN;
1435 get_commit_info(suspect->commit, &ci, 1);
1436 printf("author %s\n", ci.author);
1437 printf("author-mail %s\n", ci.author_mail);
1438 printf("author-time %lu\n", ci.author_time);
1439 printf("author-tz %s\n", ci.author_tz);
1440 printf("committer %s\n", ci.committer);
1441 printf("committer-mail %s\n", ci.committer_mail);
1442 printf("committer-time %lu\n", ci.committer_time);
1443 printf("committer-tz %s\n", ci.committer_tz);
1444 printf("summary %s\n", ci.summary);
1445 if (suspect->commit->object.flags & UNINTERESTING)
1446 printf("boundary\n");
1447 }
46e5e69d 1448 write_filename_info(suspect->path);
06f59e9f 1449 maybe_flush_or_die(stdout, "stdout");
717d1462
LT
1450 }
1451}
1452
1732a1fd
JH
1453/*
1454 * The main loop -- while the scoreboard has lines whose true origin
3dff5379 1455 * is still unknown, pick one blame_entry, and allow its current
1732a1fd
JH
1456 * suspect to pass blames to its parents.
1457 */
85af7929 1458static void assign_blame(struct scoreboard *sb, int opt)
717d1462 1459{
85af7929
JH
1460 struct rev_info *revs = sb->revs;
1461
717d1462
LT
1462 while (1) {
1463 struct blame_entry *ent;
1464 struct commit *commit;
1465 struct origin *suspect = NULL;
1466
1467 /* find one suspect to break down */
1468 for (ent = sb->ent; !suspect && ent; ent = ent->next)
1469 if (!ent->guilty)
1470 suspect = ent->suspect;
1471 if (!suspect)
1472 return; /* all done */
1473
1732a1fd
JH
1474 /*
1475 * We will use this suspect later in the loop,
1476 * so hold onto it in the meantime.
1477 */
717d1462
LT
1478 origin_incref(suspect);
1479 commit = suspect->commit;
1480 if (!commit->object.parsed)
1481 parse_commit(commit);
85af7929
JH
1482 if (reverse ||
1483 (!(commit->object.flags & UNINTERESTING) &&
1484 !(revs->max_age != -1 && commit->date < revs->max_age)))
717d1462
LT
1485 pass_blame(sb, suspect, opt);
1486 else {
1487 commit->object.flags |= UNINTERESTING;
1488 if (commit->object.parsed)
1489 mark_parents_uninteresting(commit);
1490 }
1491 /* treat root commit as boundary */
1492 if (!commit->parents && !show_root)
1493 commit->object.flags |= UNINTERESTING;
1494
1495 /* Take responsibility for the remaining entries */
1496 for (ent = sb->ent; ent; ent = ent->next)
171dccd5 1497 if (same_suspect(ent->suspect, suspect))
717d1462
LT
1498 found_guilty_entry(ent);
1499 origin_decref(suspect);
1500
1501 if (DEBUG) /* sanity */
1502 sanity_check_refcnt(sb);
1503 }
1504}
1505
1506static const char *format_time(unsigned long time, const char *tz_str,
1507 int show_raw_time)
1508{
1509 static char time_buf[128];
1510 time_t t = time;
1511 int minutes, tz;
1512 struct tm *tm;
1513
1514 if (show_raw_time) {
1515 sprintf(time_buf, "%lu %s", time, tz_str);
1516 return time_buf;
1517 }
1518
1519 tz = atoi(tz_str);
1520 minutes = tz < 0 ? -tz : tz;
1521 minutes = (minutes / 100)*60 + (minutes % 100);
1522 minutes = tz < 0 ? -minutes : minutes;
1523 t = time + minutes * 60;
1524 tm = gmtime(&t);
1525
1526 strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S ", tm);
1527 strcat(time_buf, tz_str);
1528 return time_buf;
1529}
1530
cee7f245
JH
1531#define OUTPUT_ANNOTATE_COMPAT 001
1532#define OUTPUT_LONG_OBJECT_NAME 002
1533#define OUTPUT_RAW_TIMESTAMP 004
1534#define OUTPUT_PORCELAIN 010
1535#define OUTPUT_SHOW_NAME 020
1536#define OUTPUT_SHOW_NUMBER 040
5ff62c30 1537#define OUTPUT_SHOW_SCORE 0100
093dc5be 1538#define OUTPUT_NO_AUTHOR 0200
cee7f245
JH
1539
1540static void emit_porcelain(struct scoreboard *sb, struct blame_entry *ent)
1541{
1542 int cnt;
1543 const char *cp;
1544 struct origin *suspect = ent->suspect;
1545 char hex[41];
1546
1547 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1548 printf("%s%c%d %d %d\n",
1549 hex,
1550 ent->guilty ? ' ' : '*', // purely for debugging
1551 ent->s_lno + 1,
1552 ent->lno + 1,
1553 ent->num_lines);
1554 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1555 struct commit_info ci;
1556 suspect->commit->object.flags |= METAINFO_SHOWN;
1557 get_commit_info(suspect->commit, &ci, 1);
1558 printf("author %s\n", ci.author);
1559 printf("author-mail %s\n", ci.author_mail);
1560 printf("author-time %lu\n", ci.author_time);
1561 printf("author-tz %s\n", ci.author_tz);
1562 printf("committer %s\n", ci.committer);
1563 printf("committer-mail %s\n", ci.committer_mail);
1564 printf("committer-time %lu\n", ci.committer_time);
1565 printf("committer-tz %s\n", ci.committer_tz);
46e5e69d 1566 write_filename_info(suspect->path);
cee7f245 1567 printf("summary %s\n", ci.summary);
b11121d9
JH
1568 if (suspect->commit->object.flags & UNINTERESTING)
1569 printf("boundary\n");
cee7f245
JH
1570 }
1571 else if (suspect->commit->object.flags & MORE_THAN_ONE_PATH)
46e5e69d 1572 write_filename_info(suspect->path);
cee7f245
JH
1573
1574 cp = nth_line(sb, ent->lno);
1575 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1576 char ch;
1577 if (cnt)
1578 printf("%s %d %d\n", hex,
1579 ent->s_lno + 1 + cnt,
1580 ent->lno + 1 + cnt);
1581 putchar('\t');
1582 do {
1583 ch = *cp++;
1584 putchar(ch);
1585 } while (ch != '\n' &&
1586 cp < sb->final_buf + sb->final_buf_size);
1587 }
1588}
1589
1590static void emit_other(struct scoreboard *sb, struct blame_entry *ent, int opt)
1591{
1592 int cnt;
1593 const char *cp;
1594 struct origin *suspect = ent->suspect;
1595 struct commit_info ci;
1596 char hex[41];
1597 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
1598
1599 get_commit_info(suspect->commit, &ci, 1);
1600 strcpy(hex, sha1_to_hex(suspect->commit->object.sha1));
1601
1602 cp = nth_line(sb, ent->lno);
1603 for (cnt = 0; cnt < ent->num_lines; cnt++) {
1604 char ch;
b11121d9
JH
1605 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? 40 : 8;
1606
1607 if (suspect->commit->object.flags & UNINTERESTING) {
e68989a7
JH
1608 if (blank_boundary)
1609 memset(hex, ' ', length);
7ceacdff 1610 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
4c10a5ca
JH
1611 length--;
1612 putchar('^');
1613 }
b11121d9 1614 }
cee7f245 1615
b11121d9 1616 printf("%.*s", length, hex);
cee7f245
JH
1617 if (opt & OUTPUT_ANNOTATE_COMPAT)
1618 printf("\t(%10s\t%10s\t%d)", ci.author,
1619 format_time(ci.author_time, ci.author_tz,
1620 show_raw_time),
1621 ent->lno + 1 + cnt);
1622 else {
5ff62c30 1623 if (opt & OUTPUT_SHOW_SCORE)
54a4c617
JH
1624 printf(" %*d %02d",
1625 max_score_digits, ent->score,
1626 ent->suspect->refcnt);
cee7f245
JH
1627 if (opt & OUTPUT_SHOW_NAME)
1628 printf(" %-*.*s", longest_file, longest_file,
1629 suspect->path);
1630 if (opt & OUTPUT_SHOW_NUMBER)
1631 printf(" %*d", max_orig_digits,
1632 ent->s_lno + 1 + cnt);
093dc5be 1633
ffaf9cc0
GT
1634 if (!(opt & OUTPUT_NO_AUTHOR)) {
1635 int pad = longest_author - utf8_strwidth(ci.author);
1636 printf(" (%s%*s %10s",
1637 ci.author, pad, "",
093dc5be
JH
1638 format_time(ci.author_time,
1639 ci.author_tz,
1640 show_raw_time));
ffaf9cc0 1641 }
093dc5be 1642 printf(" %*d) ",
cee7f245
JH
1643 max_digits, ent->lno + 1 + cnt);
1644 }
1645 do {
1646 ch = *cp++;
1647 putchar(ch);
1648 } while (ch != '\n' &&
1649 cp < sb->final_buf + sb->final_buf_size);
1650 }
1651}
1652
1653static void output(struct scoreboard *sb, int option)
1654{
1655 struct blame_entry *ent;
1656
1657 if (option & OUTPUT_PORCELAIN) {
1658 for (ent = sb->ent; ent; ent = ent->next) {
1659 struct blame_entry *oth;
1660 struct origin *suspect = ent->suspect;
1661 struct commit *commit = suspect->commit;
1662 if (commit->object.flags & MORE_THAN_ONE_PATH)
1663 continue;
1664 for (oth = ent->next; oth; oth = oth->next) {
1665 if ((oth->suspect->commit != commit) ||
1666 !strcmp(oth->suspect->path, suspect->path))
1667 continue;
1668 commit->object.flags |= MORE_THAN_ONE_PATH;
1669 break;
1670 }
1671 }
1672 }
1673
1674 for (ent = sb->ent; ent; ent = ent->next) {
1675 if (option & OUTPUT_PORCELAIN)
1676 emit_porcelain(sb, ent);
5ff62c30 1677 else {
cee7f245 1678 emit_other(sb, ent, option);
5ff62c30 1679 }
cee7f245
JH
1680 }
1681}
1682
1732a1fd
JH
1683/*
1684 * To allow quick access to the contents of nth line in the
1685 * final image, prepare an index in the scoreboard.
1686 */
cee7f245
JH
1687static int prepare_lines(struct scoreboard *sb)
1688{
1689 const char *buf = sb->final_buf;
1690 unsigned long len = sb->final_buf_size;
1691 int num = 0, incomplete = 0, bol = 1;
1692
1693 if (len && buf[len-1] != '\n')
1694 incomplete++; /* incomplete line at the end */
1695 while (len--) {
1696 if (bol) {
1697 sb->lineno = xrealloc(sb->lineno,
1698 sizeof(int* ) * (num + 1));
1699 sb->lineno[num] = buf - sb->final_buf;
1700 bol = 0;
1701 }
1702 if (*buf++ == '\n') {
1703 num++;
1704 bol = 1;
1705 }
1706 }
1ca6ca87
JH
1707 sb->lineno = xrealloc(sb->lineno,
1708 sizeof(int* ) * (num + incomplete + 1));
1709 sb->lineno[num + incomplete] = buf - sb->final_buf;
cee7f245
JH
1710 sb->num_lines = num + incomplete;
1711 return sb->num_lines;
1712}
1713
1732a1fd
JH
1714/*
1715 * Add phony grafts for use with -S; this is primarily to
34baebce 1716 * support git's cvsserver that wants to give a linear history
1732a1fd
JH
1717 * to its clients.
1718 */
cee7f245
JH
1719static int read_ancestry(const char *graft_file)
1720{
1721 FILE *fp = fopen(graft_file, "r");
1722 char buf[1024];
1723 if (!fp)
1724 return -1;
1725 while (fgets(buf, sizeof(buf), fp)) {
1726 /* The format is just "Commit Parent1 Parent2 ...\n" */
1727 int len = strlen(buf);
1728 struct commit_graft *graft = read_graft_line(buf, len);
8eaf7986
JH
1729 if (graft)
1730 register_commit_graft(graft, 0);
cee7f245
JH
1731 }
1732 fclose(fp);
1733 return 0;
1734}
1735
1732a1fd
JH
1736/*
1737 * How many columns do we need to show line numbers in decimal?
1738 */
cee7f245
JH
1739static int lineno_width(int lines)
1740{
f2915045 1741 int i, width;
cee7f245 1742
f2915045
JH
1743 for (width = 1, i = 10; i <= lines + 1; width++)
1744 i *= 10;
1745 return width;
cee7f245
JH
1746}
1747
1732a1fd
JH
1748/*
1749 * How many columns do we need to show line numbers, authors,
1750 * and filenames?
1751 */
cee7f245
JH
1752static void find_alignment(struct scoreboard *sb, int *option)
1753{
1754 int longest_src_lines = 0;
1755 int longest_dst_lines = 0;
5ff62c30 1756 unsigned largest_score = 0;
cee7f245
JH
1757 struct blame_entry *e;
1758
1759 for (e = sb->ent; e; e = e->next) {
1760 struct origin *suspect = e->suspect;
1761 struct commit_info ci;
1762 int num;
1763
ab3bb800
JH
1764 if (strcmp(suspect->path, sb->path))
1765 *option |= OUTPUT_SHOW_NAME;
1766 num = strlen(suspect->path);
1767 if (longest_file < num)
1768 longest_file = num;
cee7f245
JH
1769 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
1770 suspect->commit->object.flags |= METAINFO_SHOWN;
1771 get_commit_info(suspect->commit, &ci, 1);
ffaf9cc0 1772 num = utf8_strwidth(ci.author);
cee7f245
JH
1773 if (longest_author < num)
1774 longest_author = num;
1775 }
1776 num = e->s_lno + e->num_lines;
1777 if (longest_src_lines < num)
1778 longest_src_lines = num;
1779 num = e->lno + e->num_lines;
1780 if (longest_dst_lines < num)
1781 longest_dst_lines = num;
5ff62c30
JH
1782 if (largest_score < ent_score(sb, e))
1783 largest_score = ent_score(sb, e);
cee7f245
JH
1784 }
1785 max_orig_digits = lineno_width(longest_src_lines);
1786 max_digits = lineno_width(longest_dst_lines);
5ff62c30 1787 max_score_digits = lineno_width(largest_score);
cee7f245
JH
1788}
1789
1732a1fd
JH
1790/*
1791 * For debugging -- origin is refcounted, and this asserts that
1792 * we do not underflow.
1793 */
54a4c617
JH
1794static void sanity_check_refcnt(struct scoreboard *sb)
1795{
1796 int baa = 0;
1797 struct blame_entry *ent;
1798
1799 for (ent = sb->ent; ent; ent = ent->next) {
ae86ad65 1800 /* Nobody should have zero or negative refcnt */
854b97f6
JH
1801 if (ent->suspect->refcnt <= 0) {
1802 fprintf(stderr, "%s in %s has negative refcnt %d\n",
1803 ent->suspect->path,
1804 sha1_to_hex(ent->suspect->commit->object.sha1),
1805 ent->suspect->refcnt);
ae86ad65 1806 baa = 1;
854b97f6 1807 }
ae86ad65
JH
1808 }
1809 for (ent = sb->ent; ent; ent = ent->next) {
1810 /* Mark the ones that haven't been checked */
54a4c617
JH
1811 if (0 < ent->suspect->refcnt)
1812 ent->suspect->refcnt = -ent->suspect->refcnt;
54a4c617
JH
1813 }
1814 for (ent = sb->ent; ent; ent = ent->next) {
1732a1fd
JH
1815 /*
1816 * ... then pick each and see if they have the the
1817 * correct refcnt.
54a4c617
JH
1818 */
1819 int found;
1820 struct blame_entry *e;
1821 struct origin *suspect = ent->suspect;
1822
1823 if (0 < suspect->refcnt)
1824 continue;
ae86ad65 1825 suspect->refcnt = -suspect->refcnt; /* Unmark */
54a4c617
JH
1826 for (found = 0, e = sb->ent; e; e = e->next) {
1827 if (e->suspect != suspect)
1828 continue;
1829 found++;
1830 }
854b97f6
JH
1831 if (suspect->refcnt != found) {
1832 fprintf(stderr, "%s in %s has refcnt %d, not %d\n",
1833 ent->suspect->path,
1834 sha1_to_hex(ent->suspect->commit->object.sha1),
1835 ent->suspect->refcnt, found);
1836 baa = 2;
1837 }
54a4c617
JH
1838 }
1839 if (baa) {
1840 int opt = 0160;
1841 find_alignment(sb, &opt);
1842 output(sb, opt);
854b97f6 1843 die("Baa %d!", baa);
54a4c617
JH
1844 }
1845}
1846
1732a1fd
JH
1847/*
1848 * Used for the command line parsing; check if the path exists
1849 * in the working tree.
1850 */
c455c87c 1851static int has_string_in_work_tree(const char *path)
cee7f245
JH
1852{
1853 struct stat st;
1854 return !lstat(path, &st);
1855}
1856
4a0fc95f
JH
1857static unsigned parse_score(const char *arg)
1858{
1859 char *end;
1860 unsigned long score = strtoul(arg, &end, 10);
1861 if (*end)
1862 return 0;
1863 return score;
1864}
1865
20239bae
JK
1866static const char *add_prefix(const char *prefix, const char *path)
1867{
097971f5 1868 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
20239bae
JK
1869}
1870
1732a1fd
JH
1871/*
1872 * Parsing of (comma separated) one item in the -L option
1873 */
931233bc
JH
1874static const char *parse_loc(const char *spec,
1875 struct scoreboard *sb, long lno,
1876 long begin, long *ret)
1877{
1878 char *term;
1879 const char *line;
1880 long num;
1881 int reg_error;
1882 regex_t regexp;
1883 regmatch_t match[1];
1884
7bd9641d
JH
1885 /* Allow "-L <something>,+20" to mean starting at <something>
1886 * for 20 lines, or "-L <something>,-5" for 5 lines ending at
1887 * <something>.
1888 */
1889 if (1 < begin && (spec[0] == '+' || spec[0] == '-')) {
1890 num = strtol(spec + 1, &term, 10);
1891 if (term != spec + 1) {
1892 if (spec[0] == '-')
1893 num = 0 - num;
1894 if (0 < num)
1895 *ret = begin + num - 2;
1896 else if (!num)
1897 *ret = begin;
1898 else
1899 *ret = begin + num;
1900 return term;
1901 }
1902 return spec;
1903 }
931233bc
JH
1904 num = strtol(spec, &term, 10);
1905 if (term != spec) {
1906 *ret = num;
1907 return term;
1908 }
1909 if (spec[0] != '/')
1910 return spec;
1911
1912 /* it could be a regexp of form /.../ */
1913 for (term = (char*) spec + 1; *term && *term != '/'; term++) {
1914 if (*term == '\\')
1915 term++;
1916 }
1917 if (*term != '/')
1918 return spec;
1919
1920 /* try [spec+1 .. term-1] as regexp */
1921 *term = 0;
1922 begin--; /* input is in human terms */
1923 line = nth_line(sb, begin);
1924
1925 if (!(reg_error = regcomp(&regexp, spec + 1, REG_NEWLINE)) &&
1926 !(reg_error = regexec(&regexp, line, 1, match, 0))) {
1927 const char *cp = line + match[0].rm_so;
1928 const char *nline;
1929
1930 while (begin++ < lno) {
1931 nline = nth_line(sb, begin);
1932 if (line <= cp && cp < nline)
1933 break;
1934 line = nline;
1935 }
1936 *ret = begin;
1937 regfree(&regexp);
1938 *term++ = '/';
1939 return term;
1940 }
1941 else {
1942 char errbuf[1024];
1943 regerror(reg_error, &regexp, errbuf, 1024);
1944 die("-L parameter '%s': %s", spec + 1, errbuf);
1945 }
1946}
1947
1732a1fd
JH
1948/*
1949 * Parsing of -L option
1950 */
931233bc
JH
1951static void prepare_blame_range(struct scoreboard *sb,
1952 const char *bottomtop,
1953 long lno,
1954 long *bottom, long *top)
1955{
1956 const char *term;
1957
1958 term = parse_loc(bottomtop, sb, lno, 1, bottom);
1959 if (*term == ',') {
1960 term = parse_loc(term + 1, sb, lno, *bottom + 1, top);
1961 if (*term)
acca687f 1962 usage(blame_usage);
931233bc
JH
1963 }
1964 if (*term)
acca687f 1965 usage(blame_usage);
931233bc
JH
1966}
1967
ef90d6d4 1968static int git_blame_config(const char *var, const char *value, void *cb)
4c10a5ca
JH
1969{
1970 if (!strcmp(var, "blame.showroot")) {
1971 show_root = git_config_bool(var, value);
1972 return 0;
1973 }
1974 if (!strcmp(var, "blame.blankboundary")) {
1975 blank_boundary = git_config_bool(var, value);
1976 return 0;
1977 }
ef90d6d4 1978 return git_default_config(var, value, cb);
4c10a5ca
JH
1979}
1980
f6c07d7d
JH
1981/*
1982 * Prepare a dummy commit that represents the work tree (or staged) item.
1983 * Note that annotating work tree item never works in the reverse.
1984 */
1cfe7733
JH
1985static struct commit *fake_working_tree_commit(const char *path, const char *contents_from)
1986{
1987 struct commit *commit;
1988 struct origin *origin;
1989 unsigned char head_sha1[20];
f285a2d7 1990 struct strbuf buf = STRBUF_INIT;
1cfe7733 1991 const char *ident;
1cfe7733 1992 time_t now;
1cfe7733
JH
1993 int size, len;
1994 struct cache_entry *ce;
1995 unsigned mode;
1996
1997 if (get_sha1("HEAD", head_sha1))
1998 die("No such ref: HEAD");
1999
2000 time(&now);
2001 commit = xcalloc(1, sizeof(*commit));
2002 commit->parents = xcalloc(1, sizeof(*commit->parents));
2003 commit->parents->item = lookup_commit_reference(head_sha1);
2004 commit->object.parsed = 1;
2005 commit->date = now;
2006 commit->object.type = OBJ_COMMIT;
2007
2008 origin = make_origin(commit, path);
2009
2010 if (!contents_from || strcmp("-", contents_from)) {
2011 struct stat st;
2012 const char *read_from;
2013
2014 if (contents_from) {
2015 if (stat(contents_from, &st) < 0)
2016 die("Cannot stat %s", contents_from);
2017 read_from = contents_from;
2018 }
2019 else {
2020 if (lstat(path, &st) < 0)
2021 die("Cannot lstat %s", path);
2022 read_from = path;
2023 }
1cfe7733
JH
2024 mode = canon_mode(st.st_mode);
2025 switch (st.st_mode & S_IFMT) {
2026 case S_IFREG:
387e7e19
PH
2027 if (strbuf_read_file(&buf, read_from, st.st_size) != st.st_size)
2028 die("cannot open or read %s", read_from);
1cfe7733
JH
2029 break;
2030 case S_IFLNK:
edfd45d2 2031 if (strbuf_readlink(&buf, read_from, st.st_size) < 0)
1cfe7733
JH
2032 die("cannot readlink %s", read_from);
2033 break;
2034 default:
2035 die("unsupported file type %s", read_from);
2036 }
2037 }
2038 else {
2039 /* Reading from stdin */
2040 contents_from = "standard input";
1cfe7733 2041 mode = 0;
f1696ee3 2042 if (strbuf_read(&buf, 0, 0) < 0)
af6eb822 2043 die("read error %s from stdin", strerror(errno));
1cfe7733 2044 }
21e5ad50 2045 convert_to_git(path, buf.buf, buf.len, &buf, 0);
af6eb822
PH
2046 origin->file.ptr = buf.buf;
2047 origin->file.size = buf.len;
2048 pretend_sha1_file(buf.buf, buf.len, OBJ_BLOB, origin->blob_sha1);
1cfe7733
JH
2049 commit->util = origin;
2050
2051 /*
2052 * Read the current index, replace the path entry with
2053 * origin->blob_sha1 without mucking with its mode or type
2054 * bits; we are not going to write this index out -- we just
2055 * want to run "diff-index --cached".
2056 */
2057 discard_cache();
2058 read_cache();
2059
2060 len = strlen(path);
2061 if (!mode) {
2062 int pos = cache_name_pos(path, len);
2063 if (0 <= pos)
7a51ed66 2064 mode = active_cache[pos]->ce_mode;
1cfe7733
JH
2065 else
2066 /* Let's not bother reading from HEAD tree */
2067 mode = S_IFREG | 0644;
2068 }
2069 size = cache_entry_size(len);
2070 ce = xcalloc(1, size);
2071 hashcpy(ce->sha1, origin->blob_sha1);
2072 memcpy(ce->name, path, len);
2073 ce->ce_flags = create_ce_flags(len, 0);
2074 ce->ce_mode = create_ce_mode(mode);
2075 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE);
2076
2077 /*
2078 * We are not going to write this out, so this does not matter
2079 * right now, but someday we might optimize diff-index --cached
2080 * with cache-tree information.
2081 */
2082 cache_tree_invalidate_path(active_cache_tree, path);
2083
2084 commit->buffer = xmalloc(400);
2085 ident = fmt_ident("Not Committed Yet", "not.committed.yet", NULL, 0);
1bb88be9 2086 snprintf(commit->buffer, 400,
1cfe7733
JH
2087 "tree 0000000000000000000000000000000000000000\n"
2088 "parent %s\n"
2089 "author %s\n"
2090 "committer %s\n\n"
2091 "Version of %s from %s\n",
2092 sha1_to_hex(head_sha1),
2093 ident, ident, path, contents_from ? contents_from : path);
2094 return commit;
2095}
2096
85af7929 2097static const char *prepare_final(struct scoreboard *sb)
f6c07d7d
JH
2098{
2099 int i;
2100 const char *final_commit_name = NULL;
85af7929 2101 struct rev_info *revs = sb->revs;
f6c07d7d
JH
2102
2103 /*
2104 * There must be one and only one positive commit in the
2105 * revs->pending array.
2106 */
2107 for (i = 0; i < revs->pending.nr; i++) {
2108 struct object *obj = revs->pending.objects[i].item;
2109 if (obj->flags & UNINTERESTING)
2110 continue;
2111 while (obj->type == OBJ_TAG)
2112 obj = deref_tag(obj, NULL, 0);
2113 if (obj->type != OBJ_COMMIT)
2114 die("Non commit %s?", revs->pending.objects[i].name);
2115 if (sb->final)
2116 die("More than one commit to dig from %s and %s?",
2117 revs->pending.objects[i].name,
2118 final_commit_name);
2119 sb->final = (struct commit *) obj;
2120 final_commit_name = revs->pending.objects[i].name;
2121 }
2122 return final_commit_name;
2123}
2124
85af7929
JH
2125static const char *prepare_initial(struct scoreboard *sb)
2126{
2127 int i;
2128 const char *final_commit_name = NULL;
2129 struct rev_info *revs = sb->revs;
2130
2131 /*
2132 * There must be one and only one negative commit, and it must be
2133 * the boundary.
2134 */
2135 for (i = 0; i < revs->pending.nr; i++) {
2136 struct object *obj = revs->pending.objects[i].item;
2137 if (!(obj->flags & UNINTERESTING))
2138 continue;
2139 while (obj->type == OBJ_TAG)
2140 obj = deref_tag(obj, NULL, 0);
2141 if (obj->type != OBJ_COMMIT)
2142 die("Non commit %s?", revs->pending.objects[i].name);
2143 if (sb->final)
2144 die("More than one commit to dig down to %s and %s?",
2145 revs->pending.objects[i].name,
2146 final_commit_name);
2147 sb->final = (struct commit *) obj;
2148 final_commit_name = revs->pending.objects[i].name;
2149 }
2150 if (!final_commit_name)
2151 die("No commit to dig down to?");
2152 return final_commit_name;
2153}
2154
5817da01
PH
2155static int blame_copy_callback(const struct option *option, const char *arg, int unset)
2156{
2157 int *opt = option->value;
2158
2159 /*
2160 * -C enables copy from removed files;
2161 * -C -C enables copy from existing files, but only
2162 * when blaming a new file;
2163 * -C -C -C enables copy from existing files for
2164 * everybody
2165 */
2166 if (*opt & PICKAXE_BLAME_COPY_HARDER)
2167 *opt |= PICKAXE_BLAME_COPY_HARDEST;
2168 if (*opt & PICKAXE_BLAME_COPY)
2169 *opt |= PICKAXE_BLAME_COPY_HARDER;
2170 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
2171
2172 if (arg)
2173 blame_copy_score = parse_score(arg);
2174 return 0;
2175}
2176
2177static int blame_move_callback(const struct option *option, const char *arg, int unset)
2178{
2179 int *opt = option->value;
2180
2181 *opt |= PICKAXE_BLAME_MOVE;
2182
2183 if (arg)
2184 blame_move_score = parse_score(arg);
2185 return 0;
2186}
2187
2188static int blame_bottomtop_callback(const struct option *option, const char *arg, int unset)
2189{
2190 const char **bottomtop = option->value;
2191 if (!arg)
2192 return -1;
2193 if (*bottomtop)
2194 die("More than one '-L n,m' option given");
2195 *bottomtop = arg;
2196 return 0;
2197}
2198
acca687f 2199int cmd_blame(int argc, const char **argv, const char *prefix)
cee7f245
JH
2200{
2201 struct rev_info revs;
2202 const char *path;
2203 struct scoreboard sb;
2204 struct origin *o;
2205 struct blame_entry *ent;
3f8d5204 2206 long dashdash_pos, bottom, top, lno;
cee7f245 2207 const char *final_commit_name = NULL;
21666f1a 2208 enum object_type type;
5817da01
PH
2209
2210 static const char *bottomtop = NULL;
2211 static int output_option = 0, opt = 0;
2212 static int show_stats = 0;
2213 static const char *revs_file = NULL;
2214 static const char *contents_from = NULL;
2215 static const struct option options[] = {
2216 OPT_BOOLEAN(0, "incremental", &incremental, "Show blame entries as we find them, incrementally"),
2217 OPT_BOOLEAN('b', NULL, &blank_boundary, "Show blank SHA-1 for boundary commits (Default: off)"),
2218 OPT_BOOLEAN(0, "root", &show_root, "Do not treat root commits as boundaries (Default: off)"),
2219 OPT_BOOLEAN(0, "show-stats", &show_stats, "Show work cost statistics"),
2220 OPT_BIT(0, "score-debug", &output_option, "Show output score for blame entries", OUTPUT_SHOW_SCORE),
2221 OPT_BIT('f', "show-name", &output_option, "Show original filename (Default: auto)", OUTPUT_SHOW_NAME),
2222 OPT_BIT('n', "show-number", &output_option, "Show original linenumber (Default: off)", OUTPUT_SHOW_NUMBER),
2223 OPT_BIT('p', "porcelain", &output_option, "Show in a format designed for machine consumption", OUTPUT_PORCELAIN),
2224 OPT_BIT('c', NULL, &output_option, "Use the same output mode as git-annotate (Default: off)", OUTPUT_ANNOTATE_COMPAT),
2225 OPT_BIT('t', NULL, &output_option, "Show raw timestamp (Default: off)", OUTPUT_RAW_TIMESTAMP),
2226 OPT_BIT('l', NULL, &output_option, "Show long commit SHA1 (Default: off)", OUTPUT_LONG_OBJECT_NAME),
2227 OPT_BIT('s', NULL, &output_option, "Suppress author name and timestamp (Default: off)", OUTPUT_NO_AUTHOR),
2228 OPT_BIT('w', NULL, &xdl_opts, "Ignore whitespace differences", XDF_IGNORE_WHITESPACE),
2229 OPT_STRING('S', NULL, &revs_file, "file", "Use revisions from <file> instead of calling git-rev-list"),
2230 OPT_STRING(0, "contents", &contents_from, "file", "Use <file>'s contents as the final image"),
2231 { OPTION_CALLBACK, 'C', NULL, &opt, "score", "Find line copies within and across files", PARSE_OPT_OPTARG, blame_copy_callback },
2232 { OPTION_CALLBACK, 'M', NULL, &opt, "score", "Find line movements within and across files", PARSE_OPT_OPTARG, blame_move_callback },
2233 OPT_CALLBACK('L', NULL, &bottomtop, "n,m", "Process only line range n,m, counting from 1", blame_bottomtop_callback),
2234 OPT_END()
2235 };
2236
2237 struct parse_opt_ctx_t ctx;
7ceacdff 2238 int cmd_is_annotate = !strcmp(argv[0], "annotate");
e68989a7 2239
ef90d6d4 2240 git_config(git_blame_config, NULL);
5817da01 2241 init_revisions(&revs, NULL);
612702e8 2242 save_commit_buffer = 0;
3f8d5204 2243 dashdash_pos = 0;
612702e8 2244
5817da01
PH
2245 parse_options_start(&ctx, argc, argv, PARSE_OPT_KEEP_DASHDASH |
2246 PARSE_OPT_KEEP_ARGV0);
2247 for (;;) {
5817da01
PH
2248 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
2249 case PARSE_OPT_HELP:
2250 exit(129);
2251 case PARSE_OPT_DONE:
3f8d5204
PH
2252 if (ctx.argv[0])
2253 dashdash_pos = ctx.cpidx;
5817da01
PH
2254 goto parse_done;
2255 }
2256
2257 if (!strcmp(ctx.argv[0], "--reverse")) {
2258 ctx.argv[0] = "--children";
2259 reverse = 1;
2260 }
6b61ec05 2261 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
5817da01
PH
2262 }
2263parse_done:
2264 argc = parse_options_end(&ctx);
2265
7ceacdff
JH
2266 if (cmd_is_annotate)
2267 output_option |= OUTPUT_ANNOTATE_COMPAT;
2268
b3123f98
JH
2269 if (DIFF_OPT_TST(&revs.diffopt, FIND_COPIES_HARDER))
2270 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
2271 PICKAXE_BLAME_COPY_HARDER);
2272
4a0fc95f
JH
2273 if (!blame_move_score)
2274 blame_move_score = BLAME_DEFAULT_MOVE_SCORE;
2275 if (!blame_copy_score)
2276 blame_copy_score = BLAME_DEFAULT_COPY_SCORE;
2277
1732a1fd
JH
2278 /*
2279 * We have collected options unknown to us in argv[1..unk]
cee7f245 2280 * which are to be passed to revision machinery if we are
3dff5379 2281 * going to do the "bottom" processing.
cee7f245
JH
2282 *
2283 * The remaining are:
2284 *
3f8d5204
PH
2285 * (1) if dashdash_pos != 0, its either
2286 * "blame [revisions] -- <path>" or
2287 * "blame -- <path> <rev>"
cee7f245 2288 *
3f8d5204
PH
2289 * (2) otherwise, its one of the two:
2290 * "blame [revisions] <path>"
2291 * "blame <path> <rev>"
cee7f245 2292 *
3f8d5204
PH
2293 * Note that we must strip out <path> from the arguments: we do not
2294 * want the path pruning but we may want "bottom" processing.
cee7f245 2295 */
3f8d5204
PH
2296 if (dashdash_pos) {
2297 switch (argc - dashdash_pos - 1) {
2298 case 2: /* (1b) */
2299 if (argc != 4)
5817da01 2300 usage_with_options(blame_opt_usage, options);
3f8d5204
PH
2301 /* reorder for the new way: <rev> -- <path> */
2302 argv[1] = argv[3];
2303 argv[3] = argv[2];
2304 argv[2] = "--";
2305 /* FALLTHROUGH */
2306 case 1: /* (1a) */
2307 path = add_prefix(prefix, argv[--argc]);
2308 argv[argc] = NULL;
2309 break;
2310 default:
2311 usage_with_options(blame_opt_usage, options);
cee7f245 2312 }
3f8d5204
PH
2313 } else {
2314 if (argc < 2)
5817da01 2315 usage_with_options(blame_opt_usage, options);
3f8d5204 2316 path = add_prefix(prefix, argv[argc - 1]);
c455c87c 2317 if (argc == 3 && !has_string_in_work_tree(path)) { /* (2b) */
3f8d5204
PH
2318 path = add_prefix(prefix, argv[1]);
2319 argv[1] = argv[2];
cee7f245 2320 }
3f8d5204 2321 argv[argc - 1] = "--";
cee7f245 2322
3f8d5204 2323 setup_work_tree();
c455c87c 2324 if (!has_string_in_work_tree(path))
3f8d5204 2325 die("cannot stat path %s: %s", path, strerror(errno));
cee7f245
JH
2326 }
2327
3f8d5204 2328 setup_revisions(argc, argv, &revs, NULL);
cee7f245
JH
2329 memset(&sb, 0, sizeof(sb));
2330
85af7929
JH
2331 sb.revs = &revs;
2332 if (!reverse)
2333 final_commit_name = prepare_final(&sb);
2334 else if (contents_from)
2335 die("--contents and --children do not blend well.");
2336 else
2337 final_commit_name = prepare_initial(&sb);
cee7f245
JH
2338
2339 if (!sb.final) {
1732a1fd
JH
2340 /*
2341 * "--not A B -- path" without anything positive;
1cfe7733
JH
2342 * do not default to HEAD, but use the working tree
2343 * or "--contents".
1732a1fd 2344 */
1981820b 2345 setup_work_tree();
1cfe7733
JH
2346 sb.final = fake_working_tree_commit(path, contents_from);
2347 add_pending_object(&revs, &(sb.final->object), ":");
cee7f245 2348 }
1cfe7733
JH
2349 else if (contents_from)
2350 die("Cannot use --contents with final commit object name");
cee7f245 2351
1732a1fd
JH
2352 /*
2353 * If we have bottom, this will mark the ancestors of the
cee7f245
JH
2354 * bottom commits we would reach while traversing as
2355 * uninteresting.
2356 */
3d51e1b5
MK
2357 if (prepare_revision_walk(&revs))
2358 die("revision walk setup failed");
cee7f245 2359
1cfe7733
JH
2360 if (is_null_sha1(sb.final->object.sha1)) {
2361 char *buf;
2362 o = sb.final->util;
2363 buf = xmalloc(o->file.size + 1);
2364 memcpy(buf, o->file.ptr, o->file.size + 1);
2365 sb.final_buf = buf;
2366 sb.final_buf_size = o->file.size;
2367 }
2368 else {
2369 o = get_origin(&sb, sb.final, path);
2370 if (fill_blob_sha1(o))
2371 die("no such path %s in %s", path, final_commit_name);
cee7f245 2372
21666f1a 2373 sb.final_buf = read_sha1_file(o->blob_sha1, &type,
1cfe7733 2374 &sb.final_buf_size);
ab43e495
JH
2375 if (!sb.final_buf)
2376 die("Cannot read blob %s for path %s",
2377 sha1_to_hex(o->blob_sha1),
2378 path);
1cfe7733 2379 }
c2e525d9 2380 num_read_blob++;
cee7f245
JH
2381 lno = prepare_lines(&sb);
2382
931233bc
JH
2383 bottom = top = 0;
2384 if (bottomtop)
2385 prepare_blame_range(&sb, bottomtop, lno, &bottom, &top);
2386 if (bottom && top && top < bottom) {
2387 long tmp;
2388 tmp = top; top = bottom; bottom = tmp;
2389 }
cee7f245
JH
2390 if (bottom < 1)
2391 bottom = 1;
2392 if (top < 1)
2393 top = lno;
2394 bottom--;
2395 if (lno < top)
2396 die("file %s has only %lu lines", path, lno);
2397
2398 ent = xcalloc(1, sizeof(*ent));
2399 ent->lno = bottom;
2400 ent->num_lines = top - bottom;
2401 ent->suspect = o;
2402 ent->s_lno = bottom;
2403
2404 sb.ent = ent;
2405 sb.path = path;
2406
2407 if (revs_file && read_ancestry(revs_file))
2408 die("reading graft file %s failed: %s",
2409 revs_file, strerror(errno));
2410
d551a488 2411 read_mailmap(&mailmap, NULL);
f9567384 2412
b92565dc
MH
2413 if (!incremental)
2414 setup_pager();
2415
85af7929 2416 assign_blame(&sb, opt);
cee7f245 2417
717d1462
LT
2418 if (incremental)
2419 return 0;
2420
cee7f245
JH
2421 coalesce(&sb);
2422
2423 if (!(output_option & OUTPUT_PORCELAIN))
2424 find_alignment(&sb, &output_option);
2425
2426 output(&sb, output_option);
2427 free((void *)sb.final_buf);
2428 for (ent = sb.ent; ent; ) {
2429 struct blame_entry *e = ent->next;
2430 free(ent);
2431 ent = e;
2432 }
c2e525d9 2433
870b39c1 2434 if (show_stats) {
c2e525d9
JH
2435 printf("num read blob: %d\n", num_read_blob);
2436 printf("num get patch: %d\n", num_get_patch);
2437 printf("num commits: %d\n", num_commits);
2438 }
cee7f245
JH
2439 return 0;
2440}