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