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