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