Merge branch 'jk/commit-use-no-divider-with-interpret-trailers'
[alt-git.git] / builtin / blame.c
blob2df6039a6e0e139227c937023b8d8565e5ceb611
1 /*
2 * Blame
4 * Copyright (c) 2006, 2014 by its authors
5 * See COPYING for licensing conditions
6 */
8 #include "git-compat-util.h"
9 #include "alloc.h"
10 #include "config.h"
11 #include "color.h"
12 #include "builtin.h"
13 #include "environment.h"
14 #include "gettext.h"
15 #include "hex.h"
16 #include "repository.h"
17 #include "commit.h"
18 #include "diff.h"
19 #include "revision.h"
20 #include "quote.h"
21 #include "string-list.h"
22 #include "mailmap.h"
23 #include "parse-options.h"
24 #include "prio-queue.h"
25 #include "utf8.h"
26 #include "userdiff.h"
27 #include "line-range.h"
28 #include "line-log.h"
29 #include "dir.h"
30 #include "progress.h"
31 #include "object-name.h"
32 #include "object-store.h"
33 #include "pager.h"
34 #include "blame.h"
35 #include "refs.h"
36 #include "setup.h"
37 #include "tag.h"
38 #include "write-or-die.h"
40 static char blame_usage[] = N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>");
41 static char annotate_usage[] = N_("git annotate [<options>] [<rev-opts>] [<rev>] [--] <file>");
43 static const char *blame_opt_usage[] = {
44 blame_usage,
45 "",
46 N_("<rev-opts> are documented in git-rev-list(1)"),
47 NULL
50 static const char *annotate_opt_usage[] = {
51 annotate_usage,
52 "",
53 N_("<rev-opts> are documented in git-rev-list(1)"),
54 NULL
57 static int longest_file;
58 static int longest_author;
59 static int max_orig_digits;
60 static int max_digits;
61 static int max_score_digits;
62 static int show_root;
63 static int reverse;
64 static int blank_boundary;
65 static int incremental;
66 static int xdl_opts;
67 static int abbrev = -1;
68 static int no_whole_file_rename;
69 static int show_progress;
70 static char repeated_meta_color[COLOR_MAXLEN];
71 static int coloring_mode;
72 static struct string_list ignore_revs_file_list = STRING_LIST_INIT_NODUP;
73 static int mark_unblamable_lines;
74 static int mark_ignored_lines;
76 static struct date_mode blame_date_mode = { DATE_ISO8601 };
77 static size_t blame_date_width;
79 static struct string_list mailmap = STRING_LIST_INIT_NODUP;
81 #ifndef DEBUG_BLAME
82 #define DEBUG_BLAME 0
83 #endif
85 static unsigned blame_move_score;
86 static unsigned blame_copy_score;
88 /* Remember to update object flag allocation in object.h */
89 #define METAINFO_SHOWN (1u<<12)
90 #define MORE_THAN_ONE_PATH (1u<<13)
92 struct progress_info {
93 struct progress *progress;
94 int blamed_lines;
97 static const char *nth_line_cb(void *data, long lno)
99 return blame_nth_line((struct blame_scoreboard *)data, lno);
103 * Information on commits, used for output.
105 struct commit_info {
106 struct strbuf author;
107 struct strbuf author_mail;
108 timestamp_t author_time;
109 struct strbuf author_tz;
111 /* filled only when asked for details */
112 struct strbuf committer;
113 struct strbuf committer_mail;
114 timestamp_t committer_time;
115 struct strbuf committer_tz;
117 struct strbuf summary;
120 #define COMMIT_INFO_INIT { \
121 .author = STRBUF_INIT, \
122 .author_mail = STRBUF_INIT, \
123 .author_tz = STRBUF_INIT, \
124 .committer = STRBUF_INIT, \
125 .committer_mail = STRBUF_INIT, \
126 .committer_tz = STRBUF_INIT, \
127 .summary = STRBUF_INIT, \
131 * Parse author/committer line in the commit object buffer
133 static void get_ac_line(const char *inbuf, const char *what,
134 struct strbuf *name, struct strbuf *mail,
135 timestamp_t *time, struct strbuf *tz)
137 struct ident_split ident;
138 size_t len, maillen, namelen;
139 char *tmp, *endp;
140 const char *namebuf, *mailbuf;
142 tmp = strstr(inbuf, what);
143 if (!tmp)
144 goto error_out;
145 tmp += strlen(what);
146 endp = strchr(tmp, '\n');
147 if (!endp)
148 len = strlen(tmp);
149 else
150 len = endp - tmp;
152 if (split_ident_line(&ident, tmp, len)) {
153 error_out:
154 /* Ugh */
155 tmp = "(unknown)";
156 strbuf_addstr(name, tmp);
157 strbuf_addstr(mail, tmp);
158 strbuf_addstr(tz, tmp);
159 *time = 0;
160 return;
163 namelen = ident.name_end - ident.name_begin;
164 namebuf = ident.name_begin;
166 maillen = ident.mail_end - ident.mail_begin;
167 mailbuf = ident.mail_begin;
169 if (ident.date_begin && ident.date_end)
170 *time = strtoul(ident.date_begin, NULL, 10);
171 else
172 *time = 0;
174 if (ident.tz_begin && ident.tz_end)
175 strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);
176 else
177 strbuf_addstr(tz, "(unknown)");
180 * Now, convert both name and e-mail using mailmap
182 map_user(&mailmap, &mailbuf, &maillen,
183 &namebuf, &namelen);
185 strbuf_addf(mail, "<%.*s>", (int)maillen, mailbuf);
186 strbuf_add(name, namebuf, namelen);
189 static void commit_info_destroy(struct commit_info *ci)
192 strbuf_release(&ci->author);
193 strbuf_release(&ci->author_mail);
194 strbuf_release(&ci->author_tz);
195 strbuf_release(&ci->committer);
196 strbuf_release(&ci->committer_mail);
197 strbuf_release(&ci->committer_tz);
198 strbuf_release(&ci->summary);
201 static void get_commit_info(struct commit *commit,
202 struct commit_info *ret,
203 int detailed)
205 int len;
206 const char *subject, *encoding;
207 const char *message;
209 encoding = get_log_output_encoding();
210 message = repo_logmsg_reencode(the_repository, commit, NULL, encoding);
211 get_ac_line(message, "\nauthor ",
212 &ret->author, &ret->author_mail,
213 &ret->author_time, &ret->author_tz);
215 if (!detailed) {
216 repo_unuse_commit_buffer(the_repository, commit, message);
217 return;
220 get_ac_line(message, "\ncommitter ",
221 &ret->committer, &ret->committer_mail,
222 &ret->committer_time, &ret->committer_tz);
224 len = find_commit_subject(message, &subject);
225 if (len)
226 strbuf_add(&ret->summary, subject, len);
227 else
228 strbuf_addf(&ret->summary, "(%s)", oid_to_hex(&commit->object.oid));
230 repo_unuse_commit_buffer(the_repository, commit, message);
234 * Write out any suspect information which depends on the path. This must be
235 * handled separately from emit_one_suspect_detail(), because a given commit
236 * may have changes in multiple paths. So this needs to appear each time
237 * we mention a new group.
239 * To allow LF and other nonportable characters in pathnames,
240 * they are c-style quoted as needed.
242 static void write_filename_info(struct blame_origin *suspect)
244 if (suspect->previous) {
245 struct blame_origin *prev = suspect->previous;
246 printf("previous %s ", oid_to_hex(&prev->commit->object.oid));
247 write_name_quoted(prev->path, stdout, '\n');
249 printf("filename ");
250 write_name_quoted(suspect->path, stdout, '\n');
254 * Porcelain/Incremental format wants to show a lot of details per
255 * commit. Instead of repeating this every line, emit it only once,
256 * the first time each commit appears in the output (unless the
257 * user has specifically asked for us to repeat).
259 static int emit_one_suspect_detail(struct blame_origin *suspect, int repeat)
261 struct commit_info ci = COMMIT_INFO_INIT;
263 if (!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))
264 return 0;
266 suspect->commit->object.flags |= METAINFO_SHOWN;
267 get_commit_info(suspect->commit, &ci, 1);
268 printf("author %s\n", ci.author.buf);
269 printf("author-mail %s\n", ci.author_mail.buf);
270 printf("author-time %"PRItime"\n", ci.author_time);
271 printf("author-tz %s\n", ci.author_tz.buf);
272 printf("committer %s\n", ci.committer.buf);
273 printf("committer-mail %s\n", ci.committer_mail.buf);
274 printf("committer-time %"PRItime"\n", ci.committer_time);
275 printf("committer-tz %s\n", ci.committer_tz.buf);
276 printf("summary %s\n", ci.summary.buf);
277 if (suspect->commit->object.flags & UNINTERESTING)
278 printf("boundary\n");
280 commit_info_destroy(&ci);
282 return 1;
286 * The blame_entry is found to be guilty for the range.
287 * Show it in incremental output.
289 static void found_guilty_entry(struct blame_entry *ent, void *data)
291 struct progress_info *pi = (struct progress_info *)data;
293 if (incremental) {
294 struct blame_origin *suspect = ent->suspect;
296 printf("%s %d %d %d\n",
297 oid_to_hex(&suspect->commit->object.oid),
298 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
299 emit_one_suspect_detail(suspect, 0);
300 write_filename_info(suspect);
301 maybe_flush_or_die(stdout, "stdout");
303 pi->blamed_lines += ent->num_lines;
304 display_progress(pi->progress, pi->blamed_lines);
307 static const char *format_time(timestamp_t time, const char *tz_str,
308 int show_raw_time)
310 static struct strbuf time_buf = STRBUF_INIT;
312 strbuf_reset(&time_buf);
313 if (show_raw_time) {
314 strbuf_addf(&time_buf, "%"PRItime" %s", time, tz_str);
316 else {
317 const char *time_str;
318 size_t time_width;
319 int tz;
320 tz = atoi(tz_str);
321 time_str = show_date(time, tz, &blame_date_mode);
322 strbuf_addstr(&time_buf, time_str);
324 * Add space paddings to time_buf to display a fixed width
325 * string, and use time_width for display width calibration.
327 for (time_width = utf8_strwidth(time_str);
328 time_width < blame_date_width;
329 time_width++)
330 strbuf_addch(&time_buf, ' ');
332 return time_buf.buf;
335 #define OUTPUT_ANNOTATE_COMPAT (1U<<0)
336 #define OUTPUT_LONG_OBJECT_NAME (1U<<1)
337 #define OUTPUT_RAW_TIMESTAMP (1U<<2)
338 #define OUTPUT_PORCELAIN (1U<<3)
339 #define OUTPUT_SHOW_NAME (1U<<4)
340 #define OUTPUT_SHOW_NUMBER (1U<<5)
341 #define OUTPUT_SHOW_SCORE (1U<<6)
342 #define OUTPUT_NO_AUTHOR (1U<<7)
343 #define OUTPUT_SHOW_EMAIL (1U<<8)
344 #define OUTPUT_LINE_PORCELAIN (1U<<9)
345 #define OUTPUT_COLOR_LINE (1U<<10)
346 #define OUTPUT_SHOW_AGE_WITH_COLOR (1U<<11)
348 static void emit_porcelain_details(struct blame_origin *suspect, int repeat)
350 if (emit_one_suspect_detail(suspect, repeat) ||
351 (suspect->commit->object.flags & MORE_THAN_ONE_PATH))
352 write_filename_info(suspect);
355 static void emit_porcelain(struct blame_scoreboard *sb, struct blame_entry *ent,
356 int opt)
358 int repeat = opt & OUTPUT_LINE_PORCELAIN;
359 int cnt;
360 const char *cp;
361 struct blame_origin *suspect = ent->suspect;
362 char hex[GIT_MAX_HEXSZ + 1];
364 oid_to_hex_r(hex, &suspect->commit->object.oid);
365 printf("%s %d %d %d\n",
366 hex,
367 ent->s_lno + 1,
368 ent->lno + 1,
369 ent->num_lines);
370 emit_porcelain_details(suspect, repeat);
372 cp = blame_nth_line(sb, ent->lno);
373 for (cnt = 0; cnt < ent->num_lines; cnt++) {
374 char ch;
375 if (cnt) {
376 printf("%s %d %d\n", hex,
377 ent->s_lno + 1 + cnt,
378 ent->lno + 1 + cnt);
379 if (repeat)
380 emit_porcelain_details(suspect, 1);
382 putchar('\t');
383 do {
384 ch = *cp++;
385 putchar(ch);
386 } while (ch != '\n' &&
387 cp < sb->final_buf + sb->final_buf_size);
390 if (sb->final_buf_size && cp[-1] != '\n')
391 putchar('\n');
394 static struct color_field {
395 timestamp_t hop;
396 char col[COLOR_MAXLEN];
397 } *colorfield;
398 static int colorfield_nr, colorfield_alloc;
400 static void parse_color_fields(const char *s)
402 struct string_list l = STRING_LIST_INIT_DUP;
403 struct string_list_item *item;
404 enum { EXPECT_DATE, EXPECT_COLOR } next = EXPECT_COLOR;
406 colorfield_nr = 0;
408 /* Ideally this would be stripped and split at the same time? */
409 string_list_split(&l, s, ',', -1);
410 ALLOC_GROW(colorfield, colorfield_nr + 1, colorfield_alloc);
412 for_each_string_list_item(item, &l) {
413 switch (next) {
414 case EXPECT_DATE:
415 colorfield[colorfield_nr].hop = approxidate(item->string);
416 next = EXPECT_COLOR;
417 colorfield_nr++;
418 ALLOC_GROW(colorfield, colorfield_nr + 1, colorfield_alloc);
419 break;
420 case EXPECT_COLOR:
421 if (color_parse(item->string, colorfield[colorfield_nr].col))
422 die(_("expecting a color: %s"), item->string);
423 next = EXPECT_DATE;
424 break;
428 if (next == EXPECT_COLOR)
429 die(_("must end with a color"));
431 colorfield[colorfield_nr].hop = TIME_MAX;
432 string_list_clear(&l, 0);
435 static void setup_default_color_by_age(void)
437 parse_color_fields("blue,12 month ago,white,1 month ago,red");
440 static void determine_line_heat(struct commit_info *ci, const char **dest_color)
442 int i = 0;
444 while (i < colorfield_nr && ci->author_time > colorfield[i].hop)
445 i++;
447 *dest_color = colorfield[i].col;
450 static void emit_other(struct blame_scoreboard *sb, struct blame_entry *ent, int opt)
452 int cnt;
453 const char *cp;
454 struct blame_origin *suspect = ent->suspect;
455 struct commit_info ci = COMMIT_INFO_INIT;
456 char hex[GIT_MAX_HEXSZ + 1];
457 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
458 const char *default_color = NULL, *color = NULL, *reset = NULL;
460 get_commit_info(suspect->commit, &ci, 1);
461 oid_to_hex_r(hex, &suspect->commit->object.oid);
463 cp = blame_nth_line(sb, ent->lno);
465 if (opt & OUTPUT_SHOW_AGE_WITH_COLOR) {
466 determine_line_heat(&ci, &default_color);
467 color = default_color;
468 reset = GIT_COLOR_RESET;
471 for (cnt = 0; cnt < ent->num_lines; cnt++) {
472 char ch;
473 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? the_hash_algo->hexsz : abbrev;
475 if (opt & OUTPUT_COLOR_LINE) {
476 if (cnt > 0) {
477 color = repeated_meta_color;
478 reset = GIT_COLOR_RESET;
479 } else {
480 color = default_color ? default_color : NULL;
481 reset = default_color ? GIT_COLOR_RESET : NULL;
484 if (color)
485 fputs(color, stdout);
487 if (suspect->commit->object.flags & UNINTERESTING) {
488 if (blank_boundary)
489 memset(hex, ' ', length);
490 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
491 length--;
492 putchar('^');
496 if (mark_unblamable_lines && ent->unblamable) {
497 length--;
498 putchar('*');
500 if (mark_ignored_lines && ent->ignored) {
501 length--;
502 putchar('?');
504 printf("%.*s", length, hex);
505 if (opt & OUTPUT_ANNOTATE_COMPAT) {
506 const char *name;
507 if (opt & OUTPUT_SHOW_EMAIL)
508 name = ci.author_mail.buf;
509 else
510 name = ci.author.buf;
511 printf("\t(%10s\t%10s\t%d)", name,
512 format_time(ci.author_time, ci.author_tz.buf,
513 show_raw_time),
514 ent->lno + 1 + cnt);
515 } else {
516 if (opt & OUTPUT_SHOW_SCORE)
517 printf(" %*d %02d",
518 max_score_digits, ent->score,
519 ent->suspect->refcnt);
520 if (opt & OUTPUT_SHOW_NAME)
521 printf(" %-*.*s", longest_file, longest_file,
522 suspect->path);
523 if (opt & OUTPUT_SHOW_NUMBER)
524 printf(" %*d", max_orig_digits,
525 ent->s_lno + 1 + cnt);
527 if (!(opt & OUTPUT_NO_AUTHOR)) {
528 const char *name;
529 int pad;
530 if (opt & OUTPUT_SHOW_EMAIL)
531 name = ci.author_mail.buf;
532 else
533 name = ci.author.buf;
534 pad = longest_author - utf8_strwidth(name);
535 printf(" (%s%*s %10s",
536 name, pad, "",
537 format_time(ci.author_time,
538 ci.author_tz.buf,
539 show_raw_time));
541 printf(" %*d) ",
542 max_digits, ent->lno + 1 + cnt);
544 if (reset)
545 fputs(reset, stdout);
546 do {
547 ch = *cp++;
548 putchar(ch);
549 } while (ch != '\n' &&
550 cp < sb->final_buf + sb->final_buf_size);
553 if (sb->final_buf_size && cp[-1] != '\n')
554 putchar('\n');
556 commit_info_destroy(&ci);
559 static void output(struct blame_scoreboard *sb, int option)
561 struct blame_entry *ent;
563 if (option & OUTPUT_PORCELAIN) {
564 for (ent = sb->ent; ent; ent = ent->next) {
565 int count = 0;
566 struct blame_origin *suspect;
567 struct commit *commit = ent->suspect->commit;
568 if (commit->object.flags & MORE_THAN_ONE_PATH)
569 continue;
570 for (suspect = get_blame_suspects(commit); suspect; suspect = suspect->next) {
571 if (suspect->guilty && count++) {
572 commit->object.flags |= MORE_THAN_ONE_PATH;
573 break;
579 for (ent = sb->ent; ent; ent = ent->next) {
580 if (option & OUTPUT_PORCELAIN)
581 emit_porcelain(sb, ent, option);
582 else {
583 emit_other(sb, ent, option);
589 * Add phony grafts for use with -S; this is primarily to
590 * support git's cvsserver that wants to give a linear history
591 * to its clients.
593 static int read_ancestry(const char *graft_file)
595 FILE *fp = fopen_or_warn(graft_file, "r");
596 struct strbuf buf = STRBUF_INIT;
597 if (!fp)
598 return -1;
599 while (!strbuf_getwholeline(&buf, fp, '\n')) {
600 /* The format is just "Commit Parent1 Parent2 ...\n" */
601 struct commit_graft *graft = read_graft_line(&buf);
602 if (graft)
603 register_commit_graft(the_repository, graft, 0);
605 fclose(fp);
606 strbuf_release(&buf);
607 return 0;
610 static int update_auto_abbrev(int auto_abbrev, struct blame_origin *suspect)
612 const char *uniq = repo_find_unique_abbrev(the_repository,
613 &suspect->commit->object.oid,
614 auto_abbrev);
615 int len = strlen(uniq);
616 if (auto_abbrev < len)
617 return len;
618 return auto_abbrev;
622 * How many columns do we need to show line numbers, authors,
623 * and filenames?
625 static void find_alignment(struct blame_scoreboard *sb, int *option)
627 int longest_src_lines = 0;
628 int longest_dst_lines = 0;
629 unsigned largest_score = 0;
630 struct blame_entry *e;
631 int compute_auto_abbrev = (abbrev < 0);
632 int auto_abbrev = DEFAULT_ABBREV;
634 for (e = sb->ent; e; e = e->next) {
635 struct blame_origin *suspect = e->suspect;
636 int num;
638 if (compute_auto_abbrev)
639 auto_abbrev = update_auto_abbrev(auto_abbrev, suspect);
640 if (strcmp(suspect->path, sb->path))
641 *option |= OUTPUT_SHOW_NAME;
642 num = strlen(suspect->path);
643 if (longest_file < num)
644 longest_file = num;
645 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
646 struct commit_info ci = COMMIT_INFO_INIT;
647 suspect->commit->object.flags |= METAINFO_SHOWN;
648 get_commit_info(suspect->commit, &ci, 1);
649 if (*option & OUTPUT_SHOW_EMAIL)
650 num = utf8_strwidth(ci.author_mail.buf);
651 else
652 num = utf8_strwidth(ci.author.buf);
653 if (longest_author < num)
654 longest_author = num;
655 commit_info_destroy(&ci);
657 num = e->s_lno + e->num_lines;
658 if (longest_src_lines < num)
659 longest_src_lines = num;
660 num = e->lno + e->num_lines;
661 if (longest_dst_lines < num)
662 longest_dst_lines = num;
663 if (largest_score < blame_entry_score(sb, e))
664 largest_score = blame_entry_score(sb, e);
666 max_orig_digits = decimal_width(longest_src_lines);
667 max_digits = decimal_width(longest_dst_lines);
668 max_score_digits = decimal_width(largest_score);
670 if (compute_auto_abbrev)
671 /* one more abbrev length is needed for the boundary commit */
672 abbrev = auto_abbrev + 1;
675 static void sanity_check_on_fail(struct blame_scoreboard *sb, int baa)
677 int opt = OUTPUT_SHOW_SCORE | OUTPUT_SHOW_NUMBER | OUTPUT_SHOW_NAME;
678 find_alignment(sb, &opt);
679 output(sb, opt);
680 die("Baa %d!", baa);
683 static unsigned parse_score(const char *arg)
685 char *end;
686 unsigned long score = strtoul(arg, &end, 10);
687 if (*end)
688 return 0;
689 return score;
692 static const char *add_prefix(const char *prefix, const char *path)
694 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
697 static int git_blame_config(const char *var, const char *value, void *cb)
699 if (!strcmp(var, "blame.showroot")) {
700 show_root = git_config_bool(var, value);
701 return 0;
703 if (!strcmp(var, "blame.blankboundary")) {
704 blank_boundary = git_config_bool(var, value);
705 return 0;
707 if (!strcmp(var, "blame.showemail")) {
708 int *output_option = cb;
709 if (git_config_bool(var, value))
710 *output_option |= OUTPUT_SHOW_EMAIL;
711 else
712 *output_option &= ~OUTPUT_SHOW_EMAIL;
713 return 0;
715 if (!strcmp(var, "blame.date")) {
716 if (!value)
717 return config_error_nonbool(var);
718 parse_date_format(value, &blame_date_mode);
719 return 0;
721 if (!strcmp(var, "blame.ignorerevsfile")) {
722 const char *str;
723 int ret;
725 ret = git_config_pathname(&str, var, value);
726 if (ret)
727 return ret;
728 string_list_insert(&ignore_revs_file_list, str);
729 return 0;
731 if (!strcmp(var, "blame.markunblamablelines")) {
732 mark_unblamable_lines = git_config_bool(var, value);
733 return 0;
735 if (!strcmp(var, "blame.markignoredlines")) {
736 mark_ignored_lines = git_config_bool(var, value);
737 return 0;
739 if (!strcmp(var, "color.blame.repeatedlines")) {
740 if (color_parse_mem(value, strlen(value), repeated_meta_color))
741 warning(_("invalid value for '%s': '%s'"),
742 "color.blame.repeatedLines", value);
743 return 0;
745 if (!strcmp(var, "color.blame.highlightrecent")) {
746 parse_color_fields(value);
747 return 0;
750 if (!strcmp(var, "blame.coloring")) {
751 if (!strcmp(value, "repeatedLines")) {
752 coloring_mode |= OUTPUT_COLOR_LINE;
753 } else if (!strcmp(value, "highlightRecent")) {
754 coloring_mode |= OUTPUT_SHOW_AGE_WITH_COLOR;
755 } else if (!strcmp(value, "none")) {
756 coloring_mode &= ~(OUTPUT_COLOR_LINE |
757 OUTPUT_SHOW_AGE_WITH_COLOR);
758 } else {
759 warning(_("invalid value for '%s': '%s'"),
760 "blame.coloring", value);
761 return 0;
765 if (git_diff_heuristic_config(var, value, cb) < 0)
766 return -1;
767 if (userdiff_config(var, value) < 0)
768 return -1;
770 return git_default_config(var, value, cb);
773 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
775 int *opt = option->value;
777 BUG_ON_OPT_NEG(unset);
780 * -C enables copy from removed files;
781 * -C -C enables copy from existing files, but only
782 * when blaming a new file;
783 * -C -C -C enables copy from existing files for
784 * everybody
786 if (*opt & PICKAXE_BLAME_COPY_HARDER)
787 *opt |= PICKAXE_BLAME_COPY_HARDEST;
788 if (*opt & PICKAXE_BLAME_COPY)
789 *opt |= PICKAXE_BLAME_COPY_HARDER;
790 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
792 if (arg)
793 blame_copy_score = parse_score(arg);
794 return 0;
797 static int blame_move_callback(const struct option *option, const char *arg, int unset)
799 int *opt = option->value;
801 BUG_ON_OPT_NEG(unset);
803 *opt |= PICKAXE_BLAME_MOVE;
805 if (arg)
806 blame_move_score = parse_score(arg);
807 return 0;
810 static int is_a_rev(const char *name)
812 struct object_id oid;
814 if (repo_get_oid(the_repository, name, &oid))
815 return 0;
816 return OBJ_NONE < oid_object_info(the_repository, &oid, NULL);
819 static int peel_to_commit_oid(struct object_id *oid_ret, void *cbdata)
821 struct repository *r = ((struct blame_scoreboard *)cbdata)->repo;
822 struct object_id oid;
824 oidcpy(&oid, oid_ret);
825 while (1) {
826 struct object *obj;
827 int kind = oid_object_info(r, &oid, NULL);
828 if (kind == OBJ_COMMIT) {
829 oidcpy(oid_ret, &oid);
830 return 0;
832 if (kind != OBJ_TAG)
833 return -1;
834 obj = deref_tag(r, parse_object(r, &oid), NULL, 0);
835 if (!obj)
836 return -1;
837 oidcpy(&oid, &obj->oid);
841 static void build_ignorelist(struct blame_scoreboard *sb,
842 struct string_list *ignore_revs_file_list,
843 struct string_list *ignore_rev_list)
845 struct string_list_item *i;
846 struct object_id oid;
848 oidset_init(&sb->ignore_list, 0);
849 for_each_string_list_item(i, ignore_revs_file_list) {
850 if (!strcmp(i->string, ""))
851 oidset_clear(&sb->ignore_list);
852 else
853 oidset_parse_file_carefully(&sb->ignore_list, i->string,
854 peel_to_commit_oid, sb);
856 for_each_string_list_item(i, ignore_rev_list) {
857 if (repo_get_oid_committish(the_repository, i->string, &oid) ||
858 peel_to_commit_oid(&oid, sb))
859 die(_("cannot find revision %s to ignore"), i->string);
860 oidset_insert(&sb->ignore_list, &oid);
864 int cmd_blame(int argc, const char **argv, const char *prefix)
866 struct rev_info revs;
867 const char *path;
868 struct blame_scoreboard sb;
869 struct blame_origin *o;
870 struct blame_entry *ent = NULL;
871 long dashdash_pos, lno;
872 struct progress_info pi = { NULL, 0 };
874 struct string_list range_list = STRING_LIST_INIT_NODUP;
875 struct string_list ignore_rev_list = STRING_LIST_INIT_NODUP;
876 int output_option = 0, opt = 0;
877 int show_stats = 0;
878 const char *revs_file = NULL;
879 const char *contents_from = NULL;
880 const struct option options[] = {
881 OPT_BOOL(0, "incremental", &incremental, N_("show blame entries as we find them, incrementally")),
882 OPT_BOOL('b', NULL, &blank_boundary, N_("do not show object names of boundary commits (Default: off)")),
883 OPT_BOOL(0, "root", &show_root, N_("do not treat root commits as boundaries (Default: off)")),
884 OPT_BOOL(0, "show-stats", &show_stats, N_("show work cost statistics")),
885 OPT_BOOL(0, "progress", &show_progress, N_("force progress reporting")),
886 OPT_BIT(0, "score-debug", &output_option, N_("show output score for blame entries"), OUTPUT_SHOW_SCORE),
887 OPT_BIT('f', "show-name", &output_option, N_("show original filename (Default: auto)"), OUTPUT_SHOW_NAME),
888 OPT_BIT('n', "show-number", &output_option, N_("show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),
889 OPT_BIT('p', "porcelain", &output_option, N_("show in a format designed for machine consumption"), OUTPUT_PORCELAIN),
890 OPT_BIT(0, "line-porcelain", &output_option, N_("show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),
891 OPT_BIT('c', NULL, &output_option, N_("use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),
892 OPT_BIT('t', NULL, &output_option, N_("show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),
893 OPT_BIT('l', NULL, &output_option, N_("show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),
894 OPT_BIT('s', NULL, &output_option, N_("suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),
895 OPT_BIT('e', "show-email", &output_option, N_("show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),
896 OPT_BIT('w', NULL, &xdl_opts, N_("ignore whitespace differences"), XDF_IGNORE_WHITESPACE),
897 OPT_STRING_LIST(0, "ignore-rev", &ignore_rev_list, N_("rev"), N_("ignore <rev> when blaming")),
898 OPT_STRING_LIST(0, "ignore-revs-file", &ignore_revs_file_list, N_("file"), N_("ignore revisions from <file>")),
899 OPT_BIT(0, "color-lines", &output_option, N_("color redundant metadata from previous line differently"), OUTPUT_COLOR_LINE),
900 OPT_BIT(0, "color-by-age", &output_option, N_("color lines by age"), OUTPUT_SHOW_AGE_WITH_COLOR),
901 OPT_BIT(0, "minimal", &xdl_opts, N_("spend extra cycles to find better match"), XDF_NEED_MINIMAL),
902 OPT_STRING('S', NULL, &revs_file, N_("file"), N_("use revisions from <file> instead of calling git-rev-list")),
903 OPT_STRING(0, "contents", &contents_from, N_("file"), N_("use <file>'s contents as the final image")),
904 OPT_CALLBACK_F('C', NULL, &opt, N_("score"), N_("find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback),
905 OPT_CALLBACK_F('M', NULL, &opt, N_("score"), N_("find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback),
906 OPT_STRING_LIST('L', NULL, &range_list, N_("range"),
907 N_("process only line range <start>,<end> or function :<funcname>")),
908 OPT__ABBREV(&abbrev),
909 OPT_END()
912 struct parse_opt_ctx_t ctx;
913 int cmd_is_annotate = !strcmp(argv[0], "annotate");
914 struct range_set ranges;
915 unsigned int range_i;
916 long anchor;
917 const int hexsz = the_hash_algo->hexsz;
918 long num_lines = 0;
919 const char *str_usage = cmd_is_annotate ? annotate_usage : blame_usage;
920 const char **opt_usage = cmd_is_annotate ? annotate_opt_usage : blame_opt_usage;
922 setup_default_color_by_age();
923 git_config(git_blame_config, &output_option);
924 repo_init_revisions(the_repository, &revs, NULL);
925 revs.date_mode = blame_date_mode;
926 revs.diffopt.flags.allow_textconv = 1;
927 revs.diffopt.flags.follow_renames = 1;
929 save_commit_buffer = 0;
930 dashdash_pos = 0;
931 show_progress = -1;
933 parse_options_start(&ctx, argc, argv, prefix, options,
934 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);
935 for (;;) {
936 switch (parse_options_step(&ctx, options, opt_usage)) {
937 case PARSE_OPT_NON_OPTION:
938 case PARSE_OPT_UNKNOWN:
939 break;
940 case PARSE_OPT_HELP:
941 case PARSE_OPT_ERROR:
942 case PARSE_OPT_SUBCOMMAND:
943 exit(129);
944 case PARSE_OPT_COMPLETE:
945 exit(0);
946 case PARSE_OPT_DONE:
947 if (ctx.argv[0])
948 dashdash_pos = ctx.cpidx;
949 goto parse_done;
952 if (!strcmp(ctx.argv[0], "--reverse")) {
953 ctx.argv[0] = "--children";
954 reverse = 1;
956 parse_revision_opt(&revs, &ctx, options, opt_usage);
958 parse_done:
959 revision_opts_finish(&revs);
960 no_whole_file_rename = !revs.diffopt.flags.follow_renames;
961 xdl_opts |= revs.diffopt.xdl_opts & XDF_INDENT_HEURISTIC;
962 revs.diffopt.flags.follow_renames = 0;
963 argc = parse_options_end(&ctx);
965 prepare_repo_settings(the_repository);
966 the_repository->settings.command_requires_full_index = 0;
968 if (incremental || (output_option & OUTPUT_PORCELAIN)) {
969 if (show_progress > 0)
970 die(_("--progress can't be used with --incremental or porcelain formats"));
971 show_progress = 0;
972 } else if (show_progress < 0)
973 show_progress = isatty(2);
975 if (0 < abbrev && abbrev < hexsz)
976 /* one more abbrev length is needed for the boundary commit */
977 abbrev++;
978 else if (!abbrev)
979 abbrev = hexsz;
981 if (revs_file && read_ancestry(revs_file))
982 die_errno("reading graft file '%s' failed", revs_file);
984 if (cmd_is_annotate) {
985 output_option |= OUTPUT_ANNOTATE_COMPAT;
986 blame_date_mode.type = DATE_ISO8601;
987 } else {
988 blame_date_mode = revs.date_mode;
991 /* The maximum width used to show the dates */
992 switch (blame_date_mode.type) {
993 case DATE_RFC2822:
994 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");
995 break;
996 case DATE_ISO8601_STRICT:
997 blame_date_width = sizeof("2006-10-19T16:00:04-07:00");
998 break;
999 case DATE_ISO8601:
1000 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");
1001 break;
1002 case DATE_RAW:
1003 blame_date_width = sizeof("1161298804 -0700");
1004 break;
1005 case DATE_UNIX:
1006 blame_date_width = sizeof("1161298804");
1007 break;
1008 case DATE_SHORT:
1009 blame_date_width = sizeof("2006-10-19");
1010 break;
1011 case DATE_RELATIVE:
1013 * TRANSLATORS: This string is used to tell us the
1014 * maximum display width for a relative timestamp in
1015 * "git blame" output. For C locale, "4 years, 11
1016 * months ago", which takes 22 places, is the longest
1017 * among various forms of relative timestamps, but
1018 * your language may need more or fewer display
1019 * columns.
1021 blame_date_width = utf8_strwidth(_("4 years, 11 months ago")) + 1; /* add the null */
1022 break;
1023 case DATE_HUMAN:
1024 /* If the year is shown, no time is shown */
1025 blame_date_width = sizeof("Thu Oct 19 16:00");
1026 break;
1027 case DATE_NORMAL:
1028 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");
1029 break;
1030 case DATE_STRFTIME:
1031 blame_date_width = strlen(show_date(0, 0, &blame_date_mode)) + 1; /* add the null */
1032 break;
1034 blame_date_width -= 1; /* strip the null */
1036 if (revs.diffopt.flags.find_copies_harder)
1037 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
1038 PICKAXE_BLAME_COPY_HARDER);
1041 * We have collected options unknown to us in argv[1..unk]
1042 * which are to be passed to revision machinery if we are
1043 * going to do the "bottom" processing.
1045 * The remaining are:
1047 * (1) if dashdash_pos != 0, it is either
1048 * "blame [revisions] -- <path>" or
1049 * "blame -- <path> <rev>"
1051 * (2) otherwise, it is one of the two:
1052 * "blame [revisions] <path>"
1053 * "blame <path> <rev>"
1055 * Note that we must strip out <path> from the arguments: we do not
1056 * want the path pruning but we may want "bottom" processing.
1058 if (dashdash_pos) {
1059 switch (argc - dashdash_pos - 1) {
1060 case 2: /* (1b) */
1061 if (argc != 4)
1062 usage_with_options(opt_usage, options);
1063 /* reorder for the new way: <rev> -- <path> */
1064 argv[1] = argv[3];
1065 argv[3] = argv[2];
1066 argv[2] = "--";
1067 /* FALLTHROUGH */
1068 case 1: /* (1a) */
1069 path = add_prefix(prefix, argv[--argc]);
1070 argv[argc] = NULL;
1071 break;
1072 default:
1073 usage_with_options(opt_usage, options);
1075 } else {
1076 if (argc < 2)
1077 usage_with_options(opt_usage, options);
1078 if (argc == 3 && is_a_rev(argv[argc - 1])) { /* (2b) */
1079 path = add_prefix(prefix, argv[1]);
1080 argv[1] = argv[2];
1081 } else { /* (2a) */
1082 if (argc == 2 && is_a_rev(argv[1]) && !get_git_work_tree())
1083 die("missing <path> to blame");
1084 path = add_prefix(prefix, argv[argc - 1]);
1086 argv[argc - 1] = "--";
1089 revs.disable_stdin = 1;
1090 setup_revisions(argc, argv, &revs, NULL);
1091 if (!revs.pending.nr && is_bare_repository()) {
1092 struct commit *head_commit;
1093 struct object_id head_oid;
1095 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
1096 &head_oid, NULL) ||
1097 !(head_commit = lookup_commit_reference_gently(revs.repo,
1098 &head_oid, 1)))
1099 die("no such ref: HEAD");
1101 add_pending_object(&revs, &head_commit->object, "HEAD");
1104 init_scoreboard(&sb);
1105 sb.revs = &revs;
1106 sb.contents_from = contents_from;
1107 sb.reverse = reverse;
1108 sb.repo = the_repository;
1109 sb.path = path;
1110 build_ignorelist(&sb, &ignore_revs_file_list, &ignore_rev_list);
1111 string_list_clear(&ignore_revs_file_list, 0);
1112 string_list_clear(&ignore_rev_list, 0);
1113 setup_scoreboard(&sb, &o);
1116 * Changed-path Bloom filters are disabled when looking
1117 * for copies.
1119 if (!(opt & PICKAXE_BLAME_COPY))
1120 setup_blame_bloom_data(&sb);
1122 lno = sb.num_lines;
1124 if (lno && !range_list.nr)
1125 string_list_append(&range_list, "1");
1127 anchor = 1;
1128 range_set_init(&ranges, range_list.nr);
1129 for (range_i = 0; range_i < range_list.nr; ++range_i) {
1130 long bottom, top;
1131 if (parse_range_arg(range_list.items[range_i].string,
1132 nth_line_cb, &sb, lno, anchor,
1133 &bottom, &top, sb.path,
1134 the_repository->index))
1135 usage(str_usage);
1136 if ((!lno && (top || bottom)) || lno < bottom)
1137 die(Q_("file %s has only %lu line",
1138 "file %s has only %lu lines",
1139 lno), sb.path, lno);
1140 if (bottom < 1)
1141 bottom = 1;
1142 if (top < 1 || lno < top)
1143 top = lno;
1144 bottom--;
1145 range_set_append_unsafe(&ranges, bottom, top);
1146 anchor = top + 1;
1148 sort_and_merge_range_set(&ranges);
1150 for (range_i = ranges.nr; range_i > 0; --range_i) {
1151 const struct range *r = &ranges.ranges[range_i - 1];
1152 ent = blame_entry_prepend(ent, r->start, r->end, o);
1153 num_lines += (r->end - r->start);
1155 if (!num_lines)
1156 num_lines = sb.num_lines;
1158 o->suspects = ent;
1159 prio_queue_put(&sb.commits, o->commit);
1161 blame_origin_decref(o);
1163 range_set_release(&ranges);
1164 string_list_clear(&range_list, 0);
1166 sb.ent = NULL;
1168 if (blame_move_score)
1169 sb.move_score = blame_move_score;
1170 if (blame_copy_score)
1171 sb.copy_score = blame_copy_score;
1173 sb.debug = DEBUG_BLAME;
1174 sb.on_sanity_fail = &sanity_check_on_fail;
1176 sb.show_root = show_root;
1177 sb.xdl_opts = xdl_opts;
1178 sb.no_whole_file_rename = no_whole_file_rename;
1180 read_mailmap(&mailmap);
1182 sb.found_guilty_entry = &found_guilty_entry;
1183 sb.found_guilty_entry_data = &pi;
1184 if (show_progress)
1185 pi.progress = start_delayed_progress(_("Blaming lines"), num_lines);
1187 assign_blame(&sb, opt);
1189 stop_progress(&pi.progress);
1191 if (!incremental)
1192 setup_pager();
1193 else
1194 goto cleanup;
1196 blame_sort_final(&sb);
1198 blame_coalesce(&sb);
1200 if (!(output_option & (OUTPUT_COLOR_LINE | OUTPUT_SHOW_AGE_WITH_COLOR)))
1201 output_option |= coloring_mode;
1203 if (!(output_option & OUTPUT_PORCELAIN)) {
1204 find_alignment(&sb, &output_option);
1205 if (!*repeated_meta_color &&
1206 (output_option & OUTPUT_COLOR_LINE))
1207 xsnprintf(repeated_meta_color,
1208 sizeof(repeated_meta_color),
1209 "%s", GIT_COLOR_CYAN);
1211 if (output_option & OUTPUT_ANNOTATE_COMPAT)
1212 output_option &= ~(OUTPUT_COLOR_LINE | OUTPUT_SHOW_AGE_WITH_COLOR);
1214 output(&sb, output_option);
1215 free((void *)sb.final_buf);
1216 for (ent = sb.ent; ent; ) {
1217 struct blame_entry *e = ent->next;
1218 free(ent);
1219 ent = e;
1222 if (show_stats) {
1223 printf("num read blob: %d\n", sb.num_read_blob);
1224 printf("num get patch: %d\n", sb.num_get_patch);
1225 printf("num commits: %d\n", sb.num_commits);
1228 cleanup:
1229 cleanup_scoreboard(&sb);
1230 release_revisions(&revs);
1231 return 0;