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