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