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