Merge branch 'sb/blame-color'
[git/git.git] / builtin / blame.c
1 /*
2 * Blame
3 *
4 * Copyright (c) 2006, 2014 by its authors
5 * See COPYING for licensing conditions
6 */
7
8 #include "cache.h"
9 #include "config.h"
10 #include "color.h"
11 #include "builtin.h"
12 #include "commit.h"
13 #include "diff.h"
14 #include "revision.h"
15 #include "quote.h"
16 #include "string-list.h"
17 #include "mailmap.h"
18 #include "parse-options.h"
19 #include "prio-queue.h"
20 #include "utf8.h"
21 #include "userdiff.h"
22 #include "line-range.h"
23 #include "line-log.h"
24 #include "dir.h"
25 #include "progress.h"
26 #include "blame.h"
27 #include "string-list.h"
28
29 static char blame_usage[] = N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>");
30
31 static const char *blame_opt_usage[] = {
32 blame_usage,
33 "",
34 N_("<rev-opts> are documented in git-rev-list(1)"),
35 NULL
36 };
37
38 static int longest_file;
39 static int longest_author;
40 static int max_orig_digits;
41 static int max_digits;
42 static int max_score_digits;
43 static int show_root;
44 static int reverse;
45 static int blank_boundary;
46 static int incremental;
47 static int xdl_opts;
48 static int abbrev = -1;
49 static int no_whole_file_rename;
50 static int show_progress;
51 static char repeated_meta_color[COLOR_MAXLEN];
52 static int coloring_mode;
53
54 static struct date_mode blame_date_mode = { DATE_ISO8601 };
55 static size_t blame_date_width;
56
57 static struct string_list mailmap = STRING_LIST_INIT_NODUP;
58
59 #ifndef DEBUG
60 #define DEBUG 0
61 #endif
62
63 static unsigned blame_move_score;
64 static unsigned blame_copy_score;
65
66 /* Remember to update object flag allocation in object.h */
67 #define METAINFO_SHOWN (1u<<12)
68 #define MORE_THAN_ONE_PATH (1u<<13)
69
70 struct progress_info {
71 struct progress *progress;
72 int blamed_lines;
73 };
74
75 static const char *nth_line_cb(void *data, long lno)
76 {
77 return blame_nth_line((struct blame_scoreboard *)data, lno);
78 }
79
80 /*
81 * Information on commits, used for output.
82 */
83 struct commit_info {
84 struct strbuf author;
85 struct strbuf author_mail;
86 timestamp_t author_time;
87 struct strbuf author_tz;
88
89 /* filled only when asked for details */
90 struct strbuf committer;
91 struct strbuf committer_mail;
92 timestamp_t committer_time;
93 struct strbuf committer_tz;
94
95 struct strbuf summary;
96 };
97
98 /*
99 * Parse author/committer line in the commit object buffer
100 */
101 static void get_ac_line(const char *inbuf, const char *what,
102 struct strbuf *name, struct strbuf *mail,
103 timestamp_t *time, struct strbuf *tz)
104 {
105 struct ident_split ident;
106 size_t len, maillen, namelen;
107 char *tmp, *endp;
108 const char *namebuf, *mailbuf;
109
110 tmp = strstr(inbuf, what);
111 if (!tmp)
112 goto error_out;
113 tmp += strlen(what);
114 endp = strchr(tmp, '\n');
115 if (!endp)
116 len = strlen(tmp);
117 else
118 len = endp - tmp;
119
120 if (split_ident_line(&ident, tmp, len)) {
121 error_out:
122 /* Ugh */
123 tmp = "(unknown)";
124 strbuf_addstr(name, tmp);
125 strbuf_addstr(mail, tmp);
126 strbuf_addstr(tz, tmp);
127 *time = 0;
128 return;
129 }
130
131 namelen = ident.name_end - ident.name_begin;
132 namebuf = ident.name_begin;
133
134 maillen = ident.mail_end - ident.mail_begin;
135 mailbuf = ident.mail_begin;
136
137 if (ident.date_begin && ident.date_end)
138 *time = strtoul(ident.date_begin, NULL, 10);
139 else
140 *time = 0;
141
142 if (ident.tz_begin && ident.tz_end)
143 strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);
144 else
145 strbuf_addstr(tz, "(unknown)");
146
147 /*
148 * Now, convert both name and e-mail using mailmap
149 */
150 map_user(&mailmap, &mailbuf, &maillen,
151 &namebuf, &namelen);
152
153 strbuf_addf(mail, "<%.*s>", (int)maillen, mailbuf);
154 strbuf_add(name, namebuf, namelen);
155 }
156
157 static void commit_info_init(struct commit_info *ci)
158 {
159
160 strbuf_init(&ci->author, 0);
161 strbuf_init(&ci->author_mail, 0);
162 strbuf_init(&ci->author_tz, 0);
163 strbuf_init(&ci->committer, 0);
164 strbuf_init(&ci->committer_mail, 0);
165 strbuf_init(&ci->committer_tz, 0);
166 strbuf_init(&ci->summary, 0);
167 }
168
169 static void commit_info_destroy(struct commit_info *ci)
170 {
171
172 strbuf_release(&ci->author);
173 strbuf_release(&ci->author_mail);
174 strbuf_release(&ci->author_tz);
175 strbuf_release(&ci->committer);
176 strbuf_release(&ci->committer_mail);
177 strbuf_release(&ci->committer_tz);
178 strbuf_release(&ci->summary);
179 }
180
181 static void get_commit_info(struct commit *commit,
182 struct commit_info *ret,
183 int detailed)
184 {
185 int len;
186 const char *subject, *encoding;
187 const char *message;
188
189 commit_info_init(ret);
190
191 encoding = get_log_output_encoding();
192 message = logmsg_reencode(commit, NULL, encoding);
193 get_ac_line(message, "\nauthor ",
194 &ret->author, &ret->author_mail,
195 &ret->author_time, &ret->author_tz);
196
197 if (!detailed) {
198 unuse_commit_buffer(commit, message);
199 return;
200 }
201
202 get_ac_line(message, "\ncommitter ",
203 &ret->committer, &ret->committer_mail,
204 &ret->committer_time, &ret->committer_tz);
205
206 len = find_commit_subject(message, &subject);
207 if (len)
208 strbuf_add(&ret->summary, subject, len);
209 else
210 strbuf_addf(&ret->summary, "(%s)", oid_to_hex(&commit->object.oid));
211
212 unuse_commit_buffer(commit, message);
213 }
214
215 /*
216 * Write out any suspect information which depends on the path. This must be
217 * handled separately from emit_one_suspect_detail(), because a given commit
218 * may have changes in multiple paths. So this needs to appear each time
219 * we mention a new group.
220 *
221 * To allow LF and other nonportable characters in pathnames,
222 * they are c-style quoted as needed.
223 */
224 static void write_filename_info(struct blame_origin *suspect)
225 {
226 if (suspect->previous) {
227 struct blame_origin *prev = suspect->previous;
228 printf("previous %s ", oid_to_hex(&prev->commit->object.oid));
229 write_name_quoted(prev->path, stdout, '\n');
230 }
231 printf("filename ");
232 write_name_quoted(suspect->path, stdout, '\n');
233 }
234
235 /*
236 * Porcelain/Incremental format wants to show a lot of details per
237 * commit. Instead of repeating this every line, emit it only once,
238 * the first time each commit appears in the output (unless the
239 * user has specifically asked for us to repeat).
240 */
241 static int emit_one_suspect_detail(struct blame_origin *suspect, int repeat)
242 {
243 struct commit_info ci;
244
245 if (!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))
246 return 0;
247
248 suspect->commit->object.flags |= METAINFO_SHOWN;
249 get_commit_info(suspect->commit, &ci, 1);
250 printf("author %s\n", ci.author.buf);
251 printf("author-mail %s\n", ci.author_mail.buf);
252 printf("author-time %"PRItime"\n", ci.author_time);
253 printf("author-tz %s\n", ci.author_tz.buf);
254 printf("committer %s\n", ci.committer.buf);
255 printf("committer-mail %s\n", ci.committer_mail.buf);
256 printf("committer-time %"PRItime"\n", ci.committer_time);
257 printf("committer-tz %s\n", ci.committer_tz.buf);
258 printf("summary %s\n", ci.summary.buf);
259 if (suspect->commit->object.flags & UNINTERESTING)
260 printf("boundary\n");
261
262 commit_info_destroy(&ci);
263
264 return 1;
265 }
266
267 /*
268 * The blame_entry is found to be guilty for the range.
269 * Show it in incremental output.
270 */
271 static void found_guilty_entry(struct blame_entry *ent, void *data)
272 {
273 struct progress_info *pi = (struct progress_info *)data;
274
275 if (incremental) {
276 struct blame_origin *suspect = ent->suspect;
277
278 printf("%s %d %d %d\n",
279 oid_to_hex(&suspect->commit->object.oid),
280 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
281 emit_one_suspect_detail(suspect, 0);
282 write_filename_info(suspect);
283 maybe_flush_or_die(stdout, "stdout");
284 }
285 pi->blamed_lines += ent->num_lines;
286 display_progress(pi->progress, pi->blamed_lines);
287 }
288
289 static const char *format_time(timestamp_t time, const char *tz_str,
290 int show_raw_time)
291 {
292 static struct strbuf time_buf = STRBUF_INIT;
293
294 strbuf_reset(&time_buf);
295 if (show_raw_time) {
296 strbuf_addf(&time_buf, "%"PRItime" %s", time, tz_str);
297 }
298 else {
299 const char *time_str;
300 size_t time_width;
301 int tz;
302 tz = atoi(tz_str);
303 time_str = show_date(time, tz, &blame_date_mode);
304 strbuf_addstr(&time_buf, time_str);
305 /*
306 * Add space paddings to time_buf to display a fixed width
307 * string, and use time_width for display width calibration.
308 */
309 for (time_width = utf8_strwidth(time_str);
310 time_width < blame_date_width;
311 time_width++)
312 strbuf_addch(&time_buf, ' ');
313 }
314 return time_buf.buf;
315 }
316
317 #define OUTPUT_ANNOTATE_COMPAT 001
318 #define OUTPUT_LONG_OBJECT_NAME 002
319 #define OUTPUT_RAW_TIMESTAMP 004
320 #define OUTPUT_PORCELAIN 010
321 #define OUTPUT_SHOW_NAME 020
322 #define OUTPUT_SHOW_NUMBER 040
323 #define OUTPUT_SHOW_SCORE 0100
324 #define OUTPUT_NO_AUTHOR 0200
325 #define OUTPUT_SHOW_EMAIL 0400
326 #define OUTPUT_LINE_PORCELAIN 01000
327 #define OUTPUT_COLOR_LINE 02000
328 #define OUTPUT_SHOW_AGE_WITH_COLOR 04000
329
330 static void emit_porcelain_details(struct blame_origin *suspect, int repeat)
331 {
332 if (emit_one_suspect_detail(suspect, repeat) ||
333 (suspect->commit->object.flags & MORE_THAN_ONE_PATH))
334 write_filename_info(suspect);
335 }
336
337 static void emit_porcelain(struct blame_scoreboard *sb, struct blame_entry *ent,
338 int opt)
339 {
340 int repeat = opt & OUTPUT_LINE_PORCELAIN;
341 int cnt;
342 const char *cp;
343 struct blame_origin *suspect = ent->suspect;
344 char hex[GIT_MAX_HEXSZ + 1];
345
346 oid_to_hex_r(hex, &suspect->commit->object.oid);
347 printf("%s %d %d %d\n",
348 hex,
349 ent->s_lno + 1,
350 ent->lno + 1,
351 ent->num_lines);
352 emit_porcelain_details(suspect, repeat);
353
354 cp = blame_nth_line(sb, ent->lno);
355 for (cnt = 0; cnt < ent->num_lines; cnt++) {
356 char ch;
357 if (cnt) {
358 printf("%s %d %d\n", hex,
359 ent->s_lno + 1 + cnt,
360 ent->lno + 1 + cnt);
361 if (repeat)
362 emit_porcelain_details(suspect, 1);
363 }
364 putchar('\t');
365 do {
366 ch = *cp++;
367 putchar(ch);
368 } while (ch != '\n' &&
369 cp < sb->final_buf + sb->final_buf_size);
370 }
371
372 if (sb->final_buf_size && cp[-1] != '\n')
373 putchar('\n');
374 }
375
376 static struct color_field {
377 timestamp_t hop;
378 char col[COLOR_MAXLEN];
379 } *colorfield;
380 static int colorfield_nr, colorfield_alloc;
381
382 static void parse_color_fields(const char *s)
383 {
384 struct string_list l = STRING_LIST_INIT_DUP;
385 struct string_list_item *item;
386 enum { EXPECT_DATE, EXPECT_COLOR } next = EXPECT_COLOR;
387
388 colorfield_nr = 0;
389
390 /* Ideally this would be stripped and split at the same time? */
391 string_list_split(&l, s, ',', -1);
392 ALLOC_GROW(colorfield, colorfield_nr + 1, colorfield_alloc);
393
394 for_each_string_list_item(item, &l) {
395 switch (next) {
396 case EXPECT_DATE:
397 colorfield[colorfield_nr].hop = approxidate(item->string);
398 next = EXPECT_COLOR;
399 colorfield_nr++;
400 ALLOC_GROW(colorfield, colorfield_nr + 1, colorfield_alloc);
401 break;
402 case EXPECT_COLOR:
403 if (color_parse(item->string, colorfield[colorfield_nr].col))
404 die(_("expecting a color: %s"), item->string);
405 next = EXPECT_DATE;
406 break;
407 }
408 }
409
410 if (next == EXPECT_COLOR)
411 die (_("must end with a color"));
412
413 colorfield[colorfield_nr].hop = TIME_MAX;
414 }
415
416 static void setup_default_color_by_age(void)
417 {
418 parse_color_fields("blue,12 month ago,white,1 month ago,red");
419 }
420
421 static void determine_line_heat(struct blame_entry *ent, const char **dest_color)
422 {
423 int i = 0;
424 struct commit_info ci;
425 get_commit_info(ent->suspect->commit, &ci, 1);
426
427 while (i < colorfield_nr && ci.author_time > colorfield[i].hop)
428 i++;
429
430 *dest_color = colorfield[i].col;
431 }
432
433 static void emit_other(struct blame_scoreboard *sb, struct blame_entry *ent, int opt)
434 {
435 int cnt;
436 const char *cp;
437 struct blame_origin *suspect = ent->suspect;
438 struct commit_info ci;
439 char hex[GIT_MAX_HEXSZ + 1];
440 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
441 const char *default_color = NULL, *color = NULL, *reset = NULL;
442
443 get_commit_info(suspect->commit, &ci, 1);
444 oid_to_hex_r(hex, &suspect->commit->object.oid);
445
446 cp = blame_nth_line(sb, ent->lno);
447
448 if (opt & OUTPUT_SHOW_AGE_WITH_COLOR) {
449 determine_line_heat(ent, &default_color);
450 color = default_color;
451 reset = GIT_COLOR_RESET;
452 }
453
454 for (cnt = 0; cnt < ent->num_lines; cnt++) {
455 char ch;
456 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? GIT_SHA1_HEXSZ : abbrev;
457
458 if (opt & OUTPUT_COLOR_LINE) {
459 if (cnt > 0) {
460 color = repeated_meta_color;
461 reset = GIT_COLOR_RESET;
462 } else {
463 color = default_color ? default_color : NULL;
464 reset = default_color ? GIT_COLOR_RESET : NULL;
465 }
466 }
467 if (color)
468 fputs(color, stdout);
469
470 if (suspect->commit->object.flags & UNINTERESTING) {
471 if (blank_boundary)
472 memset(hex, ' ', length);
473 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
474 length--;
475 putchar('^');
476 }
477 }
478
479 printf("%.*s", length, hex);
480 if (opt & OUTPUT_ANNOTATE_COMPAT) {
481 const char *name;
482 if (opt & OUTPUT_SHOW_EMAIL)
483 name = ci.author_mail.buf;
484 else
485 name = ci.author.buf;
486 printf("\t(%10s\t%10s\t%d)", name,
487 format_time(ci.author_time, ci.author_tz.buf,
488 show_raw_time),
489 ent->lno + 1 + cnt);
490 } else {
491 if (opt & OUTPUT_SHOW_SCORE)
492 printf(" %*d %02d",
493 max_score_digits, ent->score,
494 ent->suspect->refcnt);
495 if (opt & OUTPUT_SHOW_NAME)
496 printf(" %-*.*s", longest_file, longest_file,
497 suspect->path);
498 if (opt & OUTPUT_SHOW_NUMBER)
499 printf(" %*d", max_orig_digits,
500 ent->s_lno + 1 + cnt);
501
502 if (!(opt & OUTPUT_NO_AUTHOR)) {
503 const char *name;
504 int pad;
505 if (opt & OUTPUT_SHOW_EMAIL)
506 name = ci.author_mail.buf;
507 else
508 name = ci.author.buf;
509 pad = longest_author - utf8_strwidth(name);
510 printf(" (%s%*s %10s",
511 name, pad, "",
512 format_time(ci.author_time,
513 ci.author_tz.buf,
514 show_raw_time));
515 }
516 printf(" %*d) ",
517 max_digits, ent->lno + 1 + cnt);
518 }
519 if (reset)
520 fputs(reset, stdout);
521 do {
522 ch = *cp++;
523 putchar(ch);
524 } while (ch != '\n' &&
525 cp < sb->final_buf + sb->final_buf_size);
526 }
527
528 if (sb->final_buf_size && cp[-1] != '\n')
529 putchar('\n');
530
531 commit_info_destroy(&ci);
532 }
533
534 static void output(struct blame_scoreboard *sb, int option)
535 {
536 struct blame_entry *ent;
537
538 if (option & OUTPUT_PORCELAIN) {
539 for (ent = sb->ent; ent; ent = ent->next) {
540 int count = 0;
541 struct blame_origin *suspect;
542 struct commit *commit = ent->suspect->commit;
543 if (commit->object.flags & MORE_THAN_ONE_PATH)
544 continue;
545 for (suspect = commit->util; suspect; suspect = suspect->next) {
546 if (suspect->guilty && count++) {
547 commit->object.flags |= MORE_THAN_ONE_PATH;
548 break;
549 }
550 }
551 }
552 }
553
554 for (ent = sb->ent; ent; ent = ent->next) {
555 if (option & OUTPUT_PORCELAIN)
556 emit_porcelain(sb, ent, option);
557 else {
558 emit_other(sb, ent, option);
559 }
560 }
561 }
562
563 /*
564 * Add phony grafts for use with -S; this is primarily to
565 * support git's cvsserver that wants to give a linear history
566 * to its clients.
567 */
568 static int read_ancestry(const char *graft_file)
569 {
570 FILE *fp = fopen_or_warn(graft_file, "r");
571 struct strbuf buf = STRBUF_INIT;
572 if (!fp)
573 return -1;
574 while (!strbuf_getwholeline(&buf, fp, '\n')) {
575 /* The format is just "Commit Parent1 Parent2 ...\n" */
576 struct commit_graft *graft = read_graft_line(&buf);
577 if (graft)
578 register_commit_graft(graft, 0);
579 }
580 fclose(fp);
581 strbuf_release(&buf);
582 return 0;
583 }
584
585 static int update_auto_abbrev(int auto_abbrev, struct blame_origin *suspect)
586 {
587 const char *uniq = find_unique_abbrev(&suspect->commit->object.oid,
588 auto_abbrev);
589 int len = strlen(uniq);
590 if (auto_abbrev < len)
591 return len;
592 return auto_abbrev;
593 }
594
595 /*
596 * How many columns do we need to show line numbers, authors,
597 * and filenames?
598 */
599 static void find_alignment(struct blame_scoreboard *sb, int *option)
600 {
601 int longest_src_lines = 0;
602 int longest_dst_lines = 0;
603 unsigned largest_score = 0;
604 struct blame_entry *e;
605 int compute_auto_abbrev = (abbrev < 0);
606 int auto_abbrev = DEFAULT_ABBREV;
607
608 for (e = sb->ent; e; e = e->next) {
609 struct blame_origin *suspect = e->suspect;
610 int num;
611
612 if (compute_auto_abbrev)
613 auto_abbrev = update_auto_abbrev(auto_abbrev, suspect);
614 if (strcmp(suspect->path, sb->path))
615 *option |= OUTPUT_SHOW_NAME;
616 num = strlen(suspect->path);
617 if (longest_file < num)
618 longest_file = num;
619 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
620 struct commit_info ci;
621 suspect->commit->object.flags |= METAINFO_SHOWN;
622 get_commit_info(suspect->commit, &ci, 1);
623 if (*option & OUTPUT_SHOW_EMAIL)
624 num = utf8_strwidth(ci.author_mail.buf);
625 else
626 num = utf8_strwidth(ci.author.buf);
627 if (longest_author < num)
628 longest_author = num;
629 commit_info_destroy(&ci);
630 }
631 num = e->s_lno + e->num_lines;
632 if (longest_src_lines < num)
633 longest_src_lines = num;
634 num = e->lno + e->num_lines;
635 if (longest_dst_lines < num)
636 longest_dst_lines = num;
637 if (largest_score < blame_entry_score(sb, e))
638 largest_score = blame_entry_score(sb, e);
639 }
640 max_orig_digits = decimal_width(longest_src_lines);
641 max_digits = decimal_width(longest_dst_lines);
642 max_score_digits = decimal_width(largest_score);
643
644 if (compute_auto_abbrev)
645 /* one more abbrev length is needed for the boundary commit */
646 abbrev = auto_abbrev + 1;
647 }
648
649 static void sanity_check_on_fail(struct blame_scoreboard *sb, int baa)
650 {
651 int opt = OUTPUT_SHOW_SCORE | OUTPUT_SHOW_NUMBER | OUTPUT_SHOW_NAME;
652 find_alignment(sb, &opt);
653 output(sb, opt);
654 die("Baa %d!", baa);
655 }
656
657 static unsigned parse_score(const char *arg)
658 {
659 char *end;
660 unsigned long score = strtoul(arg, &end, 10);
661 if (*end)
662 return 0;
663 return score;
664 }
665
666 static const char *add_prefix(const char *prefix, const char *path)
667 {
668 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
669 }
670
671 static int git_blame_config(const char *var, const char *value, void *cb)
672 {
673 if (!strcmp(var, "blame.showroot")) {
674 show_root = git_config_bool(var, value);
675 return 0;
676 }
677 if (!strcmp(var, "blame.blankboundary")) {
678 blank_boundary = git_config_bool(var, value);
679 return 0;
680 }
681 if (!strcmp(var, "blame.showemail")) {
682 int *output_option = cb;
683 if (git_config_bool(var, value))
684 *output_option |= OUTPUT_SHOW_EMAIL;
685 else
686 *output_option &= ~OUTPUT_SHOW_EMAIL;
687 return 0;
688 }
689 if (!strcmp(var, "blame.date")) {
690 if (!value)
691 return config_error_nonbool(var);
692 parse_date_format(value, &blame_date_mode);
693 return 0;
694 }
695 if (!strcmp(var, "color.blame.repeatedlines")) {
696 if (color_parse_mem(value, strlen(value), repeated_meta_color))
697 warning(_("invalid color '%s' in color.blame.repeatedLines"),
698 value);
699 return 0;
700 }
701 if (!strcmp(var, "color.blame.highlightrecent")) {
702 parse_color_fields(value);
703 return 0;
704 }
705
706 if (!strcmp(var, "blame.coloring")) {
707 if (!strcmp(value, "repeatedLines")) {
708 coloring_mode |= OUTPUT_COLOR_LINE;
709 } else if (!strcmp(value, "highlightRecent")) {
710 coloring_mode |= OUTPUT_SHOW_AGE_WITH_COLOR;
711 } else if (!strcmp(value, "none")) {
712 coloring_mode &= ~(OUTPUT_COLOR_LINE |
713 OUTPUT_SHOW_AGE_WITH_COLOR);
714 } else {
715 warning(_("invalid value for blame.coloring"));
716 return 0;
717 }
718 }
719
720 if (git_diff_heuristic_config(var, value, cb) < 0)
721 return -1;
722 if (userdiff_config(var, value) < 0)
723 return -1;
724
725 return git_default_config(var, value, cb);
726 }
727
728 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
729 {
730 int *opt = option->value;
731
732 /*
733 * -C enables copy from removed files;
734 * -C -C enables copy from existing files, but only
735 * when blaming a new file;
736 * -C -C -C enables copy from existing files for
737 * everybody
738 */
739 if (*opt & PICKAXE_BLAME_COPY_HARDER)
740 *opt |= PICKAXE_BLAME_COPY_HARDEST;
741 if (*opt & PICKAXE_BLAME_COPY)
742 *opt |= PICKAXE_BLAME_COPY_HARDER;
743 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
744
745 if (arg)
746 blame_copy_score = parse_score(arg);
747 return 0;
748 }
749
750 static int blame_move_callback(const struct option *option, const char *arg, int unset)
751 {
752 int *opt = option->value;
753
754 *opt |= PICKAXE_BLAME_MOVE;
755
756 if (arg)
757 blame_move_score = parse_score(arg);
758 return 0;
759 }
760
761 static int is_a_rev(const char *name)
762 {
763 struct object_id oid;
764
765 if (get_oid(name, &oid))
766 return 0;
767 return OBJ_NONE < oid_object_info(the_repository, &oid, NULL);
768 }
769
770 int cmd_blame(int argc, const char **argv, const char *prefix)
771 {
772 struct rev_info revs;
773 const char *path;
774 struct blame_scoreboard sb;
775 struct blame_origin *o;
776 struct blame_entry *ent = NULL;
777 long dashdash_pos, lno;
778 struct progress_info pi = { NULL, 0 };
779
780 struct string_list range_list = STRING_LIST_INIT_NODUP;
781 int output_option = 0, opt = 0;
782 int show_stats = 0;
783 const char *revs_file = NULL;
784 const char *contents_from = NULL;
785 const struct option options[] = {
786 OPT_BOOL(0, "incremental", &incremental, N_("Show blame entries as we find them, incrementally")),
787 OPT_BOOL('b', NULL, &blank_boundary, N_("Show blank SHA-1 for boundary commits (Default: off)")),
788 OPT_BOOL(0, "root", &show_root, N_("Do not treat root commits as boundaries (Default: off)")),
789 OPT_BOOL(0, "show-stats", &show_stats, N_("Show work cost statistics")),
790 OPT_BOOL(0, "progress", &show_progress, N_("Force progress reporting")),
791 OPT_BIT(0, "score-debug", &output_option, N_("Show output score for blame entries"), OUTPUT_SHOW_SCORE),
792 OPT_BIT('f', "show-name", &output_option, N_("Show original filename (Default: auto)"), OUTPUT_SHOW_NAME),
793 OPT_BIT('n', "show-number", &output_option, N_("Show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),
794 OPT_BIT('p', "porcelain", &output_option, N_("Show in a format designed for machine consumption"), OUTPUT_PORCELAIN),
795 OPT_BIT(0, "line-porcelain", &output_option, N_("Show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),
796 OPT_BIT('c', NULL, &output_option, N_("Use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),
797 OPT_BIT('t', NULL, &output_option, N_("Show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),
798 OPT_BIT('l', NULL, &output_option, N_("Show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),
799 OPT_BIT('s', NULL, &output_option, N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),
800 OPT_BIT('e', "show-email", &output_option, N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),
801 OPT_BIT('w', NULL, &xdl_opts, N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),
802 OPT_BIT(0, "color-lines", &output_option, N_("color redundant metadata from previous line differently"), OUTPUT_COLOR_LINE),
803 OPT_BIT(0, "color-by-age", &output_option, N_("color lines by age"), OUTPUT_SHOW_AGE_WITH_COLOR),
804
805 /*
806 * The following two options are parsed by parse_revision_opt()
807 * and are only included here to get included in the "-h"
808 * output:
809 */
810 { OPTION_LOWLEVEL_CALLBACK, 0, "indent-heuristic", NULL, NULL, N_("Use an experimental heuristic to improve diffs"), PARSE_OPT_NOARG, parse_opt_unknown_cb },
811
812 OPT_BIT(0, "minimal", &xdl_opts, N_("Spend extra cycles to find better match"), XDF_NEED_MINIMAL),
813 OPT_STRING('S', NULL, &revs_file, N_("file"), N_("Use revisions from <file> instead of calling git-rev-list")),
814 OPT_STRING(0, "contents", &contents_from, N_("file"), N_("Use <file>'s contents as the final image")),
815 { OPTION_CALLBACK, 'C', NULL, &opt, N_("score"), N_("Find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback },
816 { OPTION_CALLBACK, 'M', NULL, &opt, N_("score"), N_("Find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback },
817 OPT_STRING_LIST('L', NULL, &range_list, N_("n,m"), N_("Process only line range n,m, counting from 1")),
818 OPT__ABBREV(&abbrev),
819 OPT_END()
820 };
821
822 struct parse_opt_ctx_t ctx;
823 int cmd_is_annotate = !strcmp(argv[0], "annotate");
824 struct range_set ranges;
825 unsigned int range_i;
826 long anchor;
827
828 setup_default_color_by_age();
829 git_config(git_blame_config, &output_option);
830 init_revisions(&revs, NULL);
831 revs.date_mode = blame_date_mode;
832 revs.diffopt.flags.allow_textconv = 1;
833 revs.diffopt.flags.follow_renames = 1;
834
835 save_commit_buffer = 0;
836 dashdash_pos = 0;
837 show_progress = -1;
838
839 parse_options_start(&ctx, argc, argv, prefix, options,
840 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);
841 for (;;) {
842 switch (parse_options_step(&ctx, options, blame_opt_usage)) {
843 case PARSE_OPT_HELP:
844 case PARSE_OPT_ERROR:
845 exit(129);
846 case PARSE_OPT_DONE:
847 if (ctx.argv[0])
848 dashdash_pos = ctx.cpidx;
849 goto parse_done;
850 }
851
852 if (!strcmp(ctx.argv[0], "--reverse")) {
853 ctx.argv[0] = "--children";
854 reverse = 1;
855 }
856 parse_revision_opt(&revs, &ctx, options, blame_opt_usage);
857 }
858 parse_done:
859 no_whole_file_rename = !revs.diffopt.flags.follow_renames;
860 xdl_opts |= revs.diffopt.xdl_opts & XDF_INDENT_HEURISTIC;
861 revs.diffopt.flags.follow_renames = 0;
862 argc = parse_options_end(&ctx);
863
864 if (incremental || (output_option & OUTPUT_PORCELAIN)) {
865 if (show_progress > 0)
866 die(_("--progress can't be used with --incremental or porcelain formats"));
867 show_progress = 0;
868 } else if (show_progress < 0)
869 show_progress = isatty(2);
870
871 if (0 < abbrev && abbrev < GIT_SHA1_HEXSZ)
872 /* one more abbrev length is needed for the boundary commit */
873 abbrev++;
874 else if (!abbrev)
875 abbrev = GIT_SHA1_HEXSZ;
876
877 if (revs_file && read_ancestry(revs_file))
878 die_errno("reading graft file '%s' failed", revs_file);
879
880 if (cmd_is_annotate) {
881 output_option |= OUTPUT_ANNOTATE_COMPAT;
882 blame_date_mode.type = DATE_ISO8601;
883 } else {
884 blame_date_mode = revs.date_mode;
885 }
886
887 /* The maximum width used to show the dates */
888 switch (blame_date_mode.type) {
889 case DATE_RFC2822:
890 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");
891 break;
892 case DATE_ISO8601_STRICT:
893 blame_date_width = sizeof("2006-10-19T16:00:04-07:00");
894 break;
895 case DATE_ISO8601:
896 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");
897 break;
898 case DATE_RAW:
899 blame_date_width = sizeof("1161298804 -0700");
900 break;
901 case DATE_UNIX:
902 blame_date_width = sizeof("1161298804");
903 break;
904 case DATE_SHORT:
905 blame_date_width = sizeof("2006-10-19");
906 break;
907 case DATE_RELATIVE:
908 /*
909 * TRANSLATORS: This string is used to tell us the
910 * maximum display width for a relative timestamp in
911 * "git blame" output. For C locale, "4 years, 11
912 * months ago", which takes 22 places, is the longest
913 * among various forms of relative timestamps, but
914 * your language may need more or fewer display
915 * columns.
916 */
917 blame_date_width = utf8_strwidth(_("4 years, 11 months ago")) + 1; /* add the null */
918 break;
919 case DATE_NORMAL:
920 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");
921 break;
922 case DATE_STRFTIME:
923 blame_date_width = strlen(show_date(0, 0, &blame_date_mode)) + 1; /* add the null */
924 break;
925 }
926 blame_date_width -= 1; /* strip the null */
927
928 if (revs.diffopt.flags.find_copies_harder)
929 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
930 PICKAXE_BLAME_COPY_HARDER);
931
932 /*
933 * We have collected options unknown to us in argv[1..unk]
934 * which are to be passed to revision machinery if we are
935 * going to do the "bottom" processing.
936 *
937 * The remaining are:
938 *
939 * (1) if dashdash_pos != 0, it is either
940 * "blame [revisions] -- <path>" or
941 * "blame -- <path> <rev>"
942 *
943 * (2) otherwise, it is one of the two:
944 * "blame [revisions] <path>"
945 * "blame <path> <rev>"
946 *
947 * Note that we must strip out <path> from the arguments: we do not
948 * want the path pruning but we may want "bottom" processing.
949 */
950 if (dashdash_pos) {
951 switch (argc - dashdash_pos - 1) {
952 case 2: /* (1b) */
953 if (argc != 4)
954 usage_with_options(blame_opt_usage, options);
955 /* reorder for the new way: <rev> -- <path> */
956 argv[1] = argv[3];
957 argv[3] = argv[2];
958 argv[2] = "--";
959 /* FALLTHROUGH */
960 case 1: /* (1a) */
961 path = add_prefix(prefix, argv[--argc]);
962 argv[argc] = NULL;
963 break;
964 default:
965 usage_with_options(blame_opt_usage, options);
966 }
967 } else {
968 if (argc < 2)
969 usage_with_options(blame_opt_usage, options);
970 if (argc == 3 && is_a_rev(argv[argc - 1])) { /* (2b) */
971 path = add_prefix(prefix, argv[1]);
972 argv[1] = argv[2];
973 } else { /* (2a) */
974 if (argc == 2 && is_a_rev(argv[1]) && !get_git_work_tree())
975 die("missing <path> to blame");
976 path = add_prefix(prefix, argv[argc - 1]);
977 }
978 argv[argc - 1] = "--";
979 }
980
981 revs.disable_stdin = 1;
982 setup_revisions(argc, argv, &revs, NULL);
983
984 init_scoreboard(&sb);
985 sb.revs = &revs;
986 sb.contents_from = contents_from;
987 sb.reverse = reverse;
988 setup_scoreboard(&sb, path, &o);
989 lno = sb.num_lines;
990
991 if (lno && !range_list.nr)
992 string_list_append(&range_list, "1");
993
994 anchor = 1;
995 range_set_init(&ranges, range_list.nr);
996 for (range_i = 0; range_i < range_list.nr; ++range_i) {
997 long bottom, top;
998 if (parse_range_arg(range_list.items[range_i].string,
999 nth_line_cb, &sb, lno, anchor,
1000 &bottom, &top, sb.path))
1001 usage(blame_usage);
1002 if (lno < top || ((lno || bottom) && lno < bottom))
1003 die(Q_("file %s has only %lu line",
1004 "file %s has only %lu lines",
1005 lno), path, lno);
1006 if (bottom < 1)
1007 bottom = 1;
1008 if (top < 1)
1009 top = lno;
1010 bottom--;
1011 range_set_append_unsafe(&ranges, bottom, top);
1012 anchor = top + 1;
1013 }
1014 sort_and_merge_range_set(&ranges);
1015
1016 for (range_i = ranges.nr; range_i > 0; --range_i) {
1017 const struct range *r = &ranges.ranges[range_i - 1];
1018 ent = blame_entry_prepend(ent, r->start, r->end, o);
1019 }
1020
1021 o->suspects = ent;
1022 prio_queue_put(&sb.commits, o->commit);
1023
1024 blame_origin_decref(o);
1025
1026 range_set_release(&ranges);
1027 string_list_clear(&range_list, 0);
1028
1029 sb.ent = NULL;
1030 sb.path = path;
1031
1032 if (blame_move_score)
1033 sb.move_score = blame_move_score;
1034 if (blame_copy_score)
1035 sb.copy_score = blame_copy_score;
1036
1037 sb.debug = DEBUG;
1038 sb.on_sanity_fail = &sanity_check_on_fail;
1039
1040 sb.show_root = show_root;
1041 sb.xdl_opts = xdl_opts;
1042 sb.no_whole_file_rename = no_whole_file_rename;
1043
1044 read_mailmap(&mailmap, NULL);
1045
1046 sb.found_guilty_entry = &found_guilty_entry;
1047 sb.found_guilty_entry_data = &pi;
1048 if (show_progress)
1049 pi.progress = start_delayed_progress(_("Blaming lines"), sb.num_lines);
1050
1051 assign_blame(&sb, opt);
1052
1053 stop_progress(&pi.progress);
1054
1055 if (!incremental)
1056 setup_pager();
1057 else
1058 return 0;
1059
1060 blame_sort_final(&sb);
1061
1062 blame_coalesce(&sb);
1063
1064 if (!(output_option & (OUTPUT_COLOR_LINE | OUTPUT_SHOW_AGE_WITH_COLOR)))
1065 output_option |= coloring_mode;
1066
1067 if (!(output_option & OUTPUT_PORCELAIN)) {
1068 find_alignment(&sb, &output_option);
1069 if (!*repeated_meta_color &&
1070 (output_option & OUTPUT_COLOR_LINE))
1071 strcpy(repeated_meta_color, GIT_COLOR_CYAN);
1072 }
1073 if (output_option & OUTPUT_ANNOTATE_COMPAT)
1074 output_option &= ~(OUTPUT_COLOR_LINE | OUTPUT_SHOW_AGE_WITH_COLOR);
1075
1076 output(&sb, output_option);
1077 free((void *)sb.final_buf);
1078 for (ent = sb.ent; ent; ) {
1079 struct blame_entry *e = ent->next;
1080 free(ent);
1081 ent = e;
1082 }
1083
1084 if (show_stats) {
1085 printf("num read blob: %d\n", sb.num_read_blob);
1086 printf("num get patch: %d\n", sb.num_get_patch);
1087 printf("num commits: %d\n", sb.num_commits);
1088 }
1089 return 0;
1090 }