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