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