git-bisect-lk2009: update nist report link
[git/debian.git] / builtin / blame.c
blob71f925e456c34513b85e64e7dd6a72d510a8307e
1 /*
2 * Blame
4 * Copyright (c) 2006, 2014 by its authors
5 * See COPYING for licensing conditions
6 */
8 #include "cache.h"
9 #include "config.h"
10 #include "color.h"
11 #include "builtin.h"
12 #include "repository.h"
13 #include "commit.h"
14 #include "diff.h"
15 #include "revision.h"
16 #include "quote.h"
17 #include "string-list.h"
18 #include "mailmap.h"
19 #include "parse-options.h"
20 #include "prio-queue.h"
21 #include "utf8.h"
22 #include "userdiff.h"
23 #include "line-range.h"
24 #include "line-log.h"
25 #include "dir.h"
26 #include "progress.h"
27 #include "object-store.h"
28 #include "blame.h"
29 #include "refs.h"
30 #include "tag.h"
32 static char blame_usage[] = N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>");
33 static char annotate_usage[] = N_("git annotate [<options>] [<rev-opts>] [<rev>] [--] <file>");
35 static const char *blame_opt_usage[] = {
36 blame_usage,
37 "",
38 N_("<rev-opts> are documented in git-rev-list(1)"),
39 NULL
42 static const char *annotate_opt_usage[] = {
43 annotate_usage,
44 "",
45 N_("<rev-opts> are documented in git-rev-list(1)"),
46 NULL
49 static int longest_file;
50 static int longest_author;
51 static int max_orig_digits;
52 static int max_digits;
53 static int max_score_digits;
54 static int show_root;
55 static int reverse;
56 static int blank_boundary;
57 static int incremental;
58 static int xdl_opts;
59 static int abbrev = -1;
60 static int no_whole_file_rename;
61 static int show_progress;
62 static char repeated_meta_color[COLOR_MAXLEN];
63 static int coloring_mode;
64 static struct string_list ignore_revs_file_list = STRING_LIST_INIT_NODUP;
65 static int mark_unblamable_lines;
66 static int mark_ignored_lines;
68 static struct date_mode blame_date_mode = { DATE_ISO8601 };
69 static size_t blame_date_width;
71 static struct string_list mailmap = STRING_LIST_INIT_NODUP;
73 #ifndef DEBUG_BLAME
74 #define DEBUG_BLAME 0
75 #endif
77 static unsigned blame_move_score;
78 static unsigned blame_copy_score;
80 /* Remember to update object flag allocation in object.h */
81 #define METAINFO_SHOWN (1u<<12)
82 #define MORE_THAN_ONE_PATH (1u<<13)
84 struct progress_info {
85 struct progress *progress;
86 int blamed_lines;
89 static const char *nth_line_cb(void *data, long lno)
91 return blame_nth_line((struct blame_scoreboard *)data, lno);
95 * Information on commits, used for output.
97 struct commit_info {
98 struct strbuf author;
99 struct strbuf author_mail;
100 timestamp_t author_time;
101 struct strbuf author_tz;
103 /* filled only when asked for details */
104 struct strbuf committer;
105 struct strbuf committer_mail;
106 timestamp_t committer_time;
107 struct strbuf committer_tz;
109 struct strbuf summary;
112 #define COMMIT_INFO_INIT { \
113 .author = STRBUF_INIT, \
114 .author_mail = STRBUF_INIT, \
115 .author_tz = STRBUF_INIT, \
116 .committer = STRBUF_INIT, \
117 .committer_mail = STRBUF_INIT, \
118 .committer_tz = STRBUF_INIT, \
119 .summary = STRBUF_INIT, \
123 * Parse author/committer line in the commit object buffer
125 static void get_ac_line(const char *inbuf, const char *what,
126 struct strbuf *name, struct strbuf *mail,
127 timestamp_t *time, struct strbuf *tz)
129 struct ident_split ident;
130 size_t len, maillen, namelen;
131 char *tmp, *endp;
132 const char *namebuf, *mailbuf;
134 tmp = strstr(inbuf, what);
135 if (!tmp)
136 goto error_out;
137 tmp += strlen(what);
138 endp = strchr(tmp, '\n');
139 if (!endp)
140 len = strlen(tmp);
141 else
142 len = endp - tmp;
144 if (split_ident_line(&ident, tmp, len)) {
145 error_out:
146 /* Ugh */
147 tmp = "(unknown)";
148 strbuf_addstr(name, tmp);
149 strbuf_addstr(mail, tmp);
150 strbuf_addstr(tz, tmp);
151 *time = 0;
152 return;
155 namelen = ident.name_end - ident.name_begin;
156 namebuf = ident.name_begin;
158 maillen = ident.mail_end - ident.mail_begin;
159 mailbuf = ident.mail_begin;
161 if (ident.date_begin && ident.date_end)
162 *time = strtoul(ident.date_begin, NULL, 10);
163 else
164 *time = 0;
166 if (ident.tz_begin && ident.tz_end)
167 strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);
168 else
169 strbuf_addstr(tz, "(unknown)");
172 * Now, convert both name and e-mail using mailmap
174 map_user(&mailmap, &mailbuf, &maillen,
175 &namebuf, &namelen);
177 strbuf_addf(mail, "<%.*s>", (int)maillen, mailbuf);
178 strbuf_add(name, namebuf, namelen);
181 static void commit_info_destroy(struct commit_info *ci)
184 strbuf_release(&ci->author);
185 strbuf_release(&ci->author_mail);
186 strbuf_release(&ci->author_tz);
187 strbuf_release(&ci->committer);
188 strbuf_release(&ci->committer_mail);
189 strbuf_release(&ci->committer_tz);
190 strbuf_release(&ci->summary);
193 static void get_commit_info(struct commit *commit,
194 struct commit_info *ret,
195 int detailed)
197 int len;
198 const char *subject, *encoding;
199 const char *message;
201 encoding = get_log_output_encoding();
202 message = logmsg_reencode(commit, NULL, encoding);
203 get_ac_line(message, "\nauthor ",
204 &ret->author, &ret->author_mail,
205 &ret->author_time, &ret->author_tz);
207 if (!detailed) {
208 unuse_commit_buffer(commit, message);
209 return;
212 get_ac_line(message, "\ncommitter ",
213 &ret->committer, &ret->committer_mail,
214 &ret->committer_time, &ret->committer_tz);
216 len = find_commit_subject(message, &subject);
217 if (len)
218 strbuf_add(&ret->summary, subject, len);
219 else
220 strbuf_addf(&ret->summary, "(%s)", oid_to_hex(&commit->object.oid));
222 unuse_commit_buffer(commit, message);
226 * Write out any suspect information which depends on the path. This must be
227 * handled separately from emit_one_suspect_detail(), because a given commit
228 * may have changes in multiple paths. So this needs to appear each time
229 * we mention a new group.
231 * To allow LF and other nonportable characters in pathnames,
232 * they are c-style quoted as needed.
234 static void write_filename_info(struct blame_origin *suspect)
236 if (suspect->previous) {
237 struct blame_origin *prev = suspect->previous;
238 printf("previous %s ", oid_to_hex(&prev->commit->object.oid));
239 write_name_quoted(prev->path, stdout, '\n');
241 printf("filename ");
242 write_name_quoted(suspect->path, stdout, '\n');
246 * Porcelain/Incremental format wants to show a lot of details per
247 * commit. Instead of repeating this every line, emit it only once,
248 * the first time each commit appears in the output (unless the
249 * user has specifically asked for us to repeat).
251 static int emit_one_suspect_detail(struct blame_origin *suspect, int repeat)
253 struct commit_info ci = COMMIT_INFO_INIT;
255 if (!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))
256 return 0;
258 suspect->commit->object.flags |= METAINFO_SHOWN;
259 get_commit_info(suspect->commit, &ci, 1);
260 printf("author %s\n", ci.author.buf);
261 printf("author-mail %s\n", ci.author_mail.buf);
262 printf("author-time %"PRItime"\n", ci.author_time);
263 printf("author-tz %s\n", ci.author_tz.buf);
264 printf("committer %s\n", ci.committer.buf);
265 printf("committer-mail %s\n", ci.committer_mail.buf);
266 printf("committer-time %"PRItime"\n", ci.committer_time);
267 printf("committer-tz %s\n", ci.committer_tz.buf);
268 printf("summary %s\n", ci.summary.buf);
269 if (suspect->commit->object.flags & UNINTERESTING)
270 printf("boundary\n");
272 commit_info_destroy(&ci);
274 return 1;
278 * The blame_entry is found to be guilty for the range.
279 * Show it in incremental output.
281 static void found_guilty_entry(struct blame_entry *ent, void *data)
283 struct progress_info *pi = (struct progress_info *)data;
285 if (incremental) {
286 struct blame_origin *suspect = ent->suspect;
288 printf("%s %d %d %d\n",
289 oid_to_hex(&suspect->commit->object.oid),
290 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
291 emit_one_suspect_detail(suspect, 0);
292 write_filename_info(suspect);
293 maybe_flush_or_die(stdout, "stdout");
295 pi->blamed_lines += ent->num_lines;
296 display_progress(pi->progress, pi->blamed_lines);
299 static const char *format_time(timestamp_t time, const char *tz_str,
300 int show_raw_time)
302 static struct strbuf time_buf = STRBUF_INIT;
304 strbuf_reset(&time_buf);
305 if (show_raw_time) {
306 strbuf_addf(&time_buf, "%"PRItime" %s", time, tz_str);
308 else {
309 const char *time_str;
310 size_t time_width;
311 int tz;
312 tz = atoi(tz_str);
313 time_str = show_date(time, tz, &blame_date_mode);
314 strbuf_addstr(&time_buf, time_str);
316 * Add space paddings to time_buf to display a fixed width
317 * string, and use time_width for display width calibration.
319 for (time_width = utf8_strwidth(time_str);
320 time_width < blame_date_width;
321 time_width++)
322 strbuf_addch(&time_buf, ' ');
324 return time_buf.buf;
327 #define OUTPUT_ANNOTATE_COMPAT (1U<<0)
328 #define OUTPUT_LONG_OBJECT_NAME (1U<<1)
329 #define OUTPUT_RAW_TIMESTAMP (1U<<2)
330 #define OUTPUT_PORCELAIN (1U<<3)
331 #define OUTPUT_SHOW_NAME (1U<<4)
332 #define OUTPUT_SHOW_NUMBER (1U<<5)
333 #define OUTPUT_SHOW_SCORE (1U<<6)
334 #define OUTPUT_NO_AUTHOR (1U<<7)
335 #define OUTPUT_SHOW_EMAIL (1U<<8)
336 #define OUTPUT_LINE_PORCELAIN (1U<<9)
337 #define OUTPUT_COLOR_LINE (1U<<10)
338 #define OUTPUT_SHOW_AGE_WITH_COLOR (1U<<11)
340 static void emit_porcelain_details(struct blame_origin *suspect, int repeat)
342 if (emit_one_suspect_detail(suspect, repeat) ||
343 (suspect->commit->object.flags & MORE_THAN_ONE_PATH))
344 write_filename_info(suspect);
347 static void emit_porcelain(struct blame_scoreboard *sb, struct blame_entry *ent,
348 int opt)
350 int repeat = opt & OUTPUT_LINE_PORCELAIN;
351 int cnt;
352 const char *cp;
353 struct blame_origin *suspect = ent->suspect;
354 char hex[GIT_MAX_HEXSZ + 1];
356 oid_to_hex_r(hex, &suspect->commit->object.oid);
357 printf("%s %d %d %d\n",
358 hex,
359 ent->s_lno + 1,
360 ent->lno + 1,
361 ent->num_lines);
362 emit_porcelain_details(suspect, repeat);
364 cp = blame_nth_line(sb, ent->lno);
365 for (cnt = 0; cnt < ent->num_lines; cnt++) {
366 char ch;
367 if (cnt) {
368 printf("%s %d %d\n", hex,
369 ent->s_lno + 1 + cnt,
370 ent->lno + 1 + cnt);
371 if (repeat)
372 emit_porcelain_details(suspect, 1);
374 putchar('\t');
375 do {
376 ch = *cp++;
377 putchar(ch);
378 } while (ch != '\n' &&
379 cp < sb->final_buf + sb->final_buf_size);
382 if (sb->final_buf_size && cp[-1] != '\n')
383 putchar('\n');
386 static struct color_field {
387 timestamp_t hop;
388 char col[COLOR_MAXLEN];
389 } *colorfield;
390 static int colorfield_nr, colorfield_alloc;
392 static void parse_color_fields(const char *s)
394 struct string_list l = STRING_LIST_INIT_DUP;
395 struct string_list_item *item;
396 enum { EXPECT_DATE, EXPECT_COLOR } next = EXPECT_COLOR;
398 colorfield_nr = 0;
400 /* Ideally this would be stripped and split at the same time? */
401 string_list_split(&l, s, ',', -1);
402 ALLOC_GROW(colorfield, colorfield_nr + 1, colorfield_alloc);
404 for_each_string_list_item(item, &l) {
405 switch (next) {
406 case EXPECT_DATE:
407 colorfield[colorfield_nr].hop = approxidate(item->string);
408 next = EXPECT_COLOR;
409 colorfield_nr++;
410 ALLOC_GROW(colorfield, colorfield_nr + 1, colorfield_alloc);
411 break;
412 case EXPECT_COLOR:
413 if (color_parse(item->string, colorfield[colorfield_nr].col))
414 die(_("expecting a color: %s"), item->string);
415 next = EXPECT_DATE;
416 break;
420 if (next == EXPECT_COLOR)
421 die(_("must end with a color"));
423 colorfield[colorfield_nr].hop = TIME_MAX;
424 string_list_clear(&l, 0);
427 static void setup_default_color_by_age(void)
429 parse_color_fields("blue,12 month ago,white,1 month ago,red");
432 static void determine_line_heat(struct commit_info *ci, const char **dest_color)
434 int i = 0;
436 while (i < colorfield_nr && ci->author_time > colorfield[i].hop)
437 i++;
439 *dest_color = colorfield[i].col;
442 static void emit_other(struct blame_scoreboard *sb, struct blame_entry *ent, int opt)
444 int cnt;
445 const char *cp;
446 struct blame_origin *suspect = ent->suspect;
447 struct commit_info ci = COMMIT_INFO_INIT;
448 char hex[GIT_MAX_HEXSZ + 1];
449 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
450 const char *default_color = NULL, *color = NULL, *reset = NULL;
452 get_commit_info(suspect->commit, &ci, 1);
453 oid_to_hex_r(hex, &suspect->commit->object.oid);
455 cp = blame_nth_line(sb, ent->lno);
457 if (opt & OUTPUT_SHOW_AGE_WITH_COLOR) {
458 determine_line_heat(&ci, &default_color);
459 color = default_color;
460 reset = GIT_COLOR_RESET;
463 for (cnt = 0; cnt < ent->num_lines; cnt++) {
464 char ch;
465 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? the_hash_algo->hexsz : abbrev;
467 if (opt & OUTPUT_COLOR_LINE) {
468 if (cnt > 0) {
469 color = repeated_meta_color;
470 reset = GIT_COLOR_RESET;
471 } else {
472 color = default_color ? default_color : NULL;
473 reset = default_color ? GIT_COLOR_RESET : NULL;
476 if (color)
477 fputs(color, stdout);
479 if (suspect->commit->object.flags & UNINTERESTING) {
480 if (blank_boundary)
481 memset(hex, ' ', length);
482 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
483 length--;
484 putchar('^');
488 if (mark_unblamable_lines && ent->unblamable) {
489 length--;
490 putchar('*');
492 if (mark_ignored_lines && ent->ignored) {
493 length--;
494 putchar('?');
496 printf("%.*s", length, hex);
497 if (opt & OUTPUT_ANNOTATE_COMPAT) {
498 const char *name;
499 if (opt & OUTPUT_SHOW_EMAIL)
500 name = ci.author_mail.buf;
501 else
502 name = ci.author.buf;
503 printf("\t(%10s\t%10s\t%d)", name,
504 format_time(ci.author_time, ci.author_tz.buf,
505 show_raw_time),
506 ent->lno + 1 + cnt);
507 } else {
508 if (opt & OUTPUT_SHOW_SCORE)
509 printf(" %*d %02d",
510 max_score_digits, ent->score,
511 ent->suspect->refcnt);
512 if (opt & OUTPUT_SHOW_NAME)
513 printf(" %-*.*s", longest_file, longest_file,
514 suspect->path);
515 if (opt & OUTPUT_SHOW_NUMBER)
516 printf(" %*d", max_orig_digits,
517 ent->s_lno + 1 + cnt);
519 if (!(opt & OUTPUT_NO_AUTHOR)) {
520 const char *name;
521 int pad;
522 if (opt & OUTPUT_SHOW_EMAIL)
523 name = ci.author_mail.buf;
524 else
525 name = ci.author.buf;
526 pad = longest_author - utf8_strwidth(name);
527 printf(" (%s%*s %10s",
528 name, pad, "",
529 format_time(ci.author_time,
530 ci.author_tz.buf,
531 show_raw_time));
533 printf(" %*d) ",
534 max_digits, ent->lno + 1 + cnt);
536 if (reset)
537 fputs(reset, stdout);
538 do {
539 ch = *cp++;
540 putchar(ch);
541 } while (ch != '\n' &&
542 cp < sb->final_buf + sb->final_buf_size);
545 if (sb->final_buf_size && cp[-1] != '\n')
546 putchar('\n');
548 commit_info_destroy(&ci);
551 static void output(struct blame_scoreboard *sb, int option)
553 struct blame_entry *ent;
555 if (option & OUTPUT_PORCELAIN) {
556 for (ent = sb->ent; ent; ent = ent->next) {
557 int count = 0;
558 struct blame_origin *suspect;
559 struct commit *commit = ent->suspect->commit;
560 if (commit->object.flags & MORE_THAN_ONE_PATH)
561 continue;
562 for (suspect = get_blame_suspects(commit); suspect; suspect = suspect->next) {
563 if (suspect->guilty && count++) {
564 commit->object.flags |= MORE_THAN_ONE_PATH;
565 break;
571 for (ent = sb->ent; ent; ent = ent->next) {
572 if (option & OUTPUT_PORCELAIN)
573 emit_porcelain(sb, ent, option);
574 else {
575 emit_other(sb, ent, option);
581 * Add phony grafts for use with -S; this is primarily to
582 * support git's cvsserver that wants to give a linear history
583 * to its clients.
585 static int read_ancestry(const char *graft_file)
587 FILE *fp = fopen_or_warn(graft_file, "r");
588 struct strbuf buf = STRBUF_INIT;
589 if (!fp)
590 return -1;
591 while (!strbuf_getwholeline(&buf, fp, '\n')) {
592 /* The format is just "Commit Parent1 Parent2 ...\n" */
593 struct commit_graft *graft = read_graft_line(&buf);
594 if (graft)
595 register_commit_graft(the_repository, graft, 0);
597 fclose(fp);
598 strbuf_release(&buf);
599 return 0;
602 static int update_auto_abbrev(int auto_abbrev, struct blame_origin *suspect)
604 const char *uniq = find_unique_abbrev(&suspect->commit->object.oid,
605 auto_abbrev);
606 int len = strlen(uniq);
607 if (auto_abbrev < len)
608 return len;
609 return auto_abbrev;
613 * How many columns do we need to show line numbers, authors,
614 * and filenames?
616 static void find_alignment(struct blame_scoreboard *sb, int *option)
618 int longest_src_lines = 0;
619 int longest_dst_lines = 0;
620 unsigned largest_score = 0;
621 struct blame_entry *e;
622 int compute_auto_abbrev = (abbrev < 0);
623 int auto_abbrev = DEFAULT_ABBREV;
625 for (e = sb->ent; e; e = e->next) {
626 struct blame_origin *suspect = e->suspect;
627 int num;
629 if (compute_auto_abbrev)
630 auto_abbrev = update_auto_abbrev(auto_abbrev, suspect);
631 if (strcmp(suspect->path, sb->path))
632 *option |= OUTPUT_SHOW_NAME;
633 num = strlen(suspect->path);
634 if (longest_file < num)
635 longest_file = num;
636 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
637 struct commit_info ci = COMMIT_INFO_INIT;
638 suspect->commit->object.flags |= METAINFO_SHOWN;
639 get_commit_info(suspect->commit, &ci, 1);
640 if (*option & OUTPUT_SHOW_EMAIL)
641 num = utf8_strwidth(ci.author_mail.buf);
642 else
643 num = utf8_strwidth(ci.author.buf);
644 if (longest_author < num)
645 longest_author = num;
646 commit_info_destroy(&ci);
648 num = e->s_lno + e->num_lines;
649 if (longest_src_lines < num)
650 longest_src_lines = num;
651 num = e->lno + e->num_lines;
652 if (longest_dst_lines < num)
653 longest_dst_lines = num;
654 if (largest_score < blame_entry_score(sb, e))
655 largest_score = blame_entry_score(sb, e);
657 max_orig_digits = decimal_width(longest_src_lines);
658 max_digits = decimal_width(longest_dst_lines);
659 max_score_digits = decimal_width(largest_score);
661 if (compute_auto_abbrev)
662 /* one more abbrev length is needed for the boundary commit */
663 abbrev = auto_abbrev + 1;
666 static void sanity_check_on_fail(struct blame_scoreboard *sb, int baa)
668 int opt = OUTPUT_SHOW_SCORE | OUTPUT_SHOW_NUMBER | OUTPUT_SHOW_NAME;
669 find_alignment(sb, &opt);
670 output(sb, opt);
671 die("Baa %d!", baa);
674 static unsigned parse_score(const char *arg)
676 char *end;
677 unsigned long score = strtoul(arg, &end, 10);
678 if (*end)
679 return 0;
680 return score;
683 static const char *add_prefix(const char *prefix, const char *path)
685 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
688 static int git_blame_config(const char *var, const char *value, void *cb)
690 if (!strcmp(var, "blame.showroot")) {
691 show_root = git_config_bool(var, value);
692 return 0;
694 if (!strcmp(var, "blame.blankboundary")) {
695 blank_boundary = git_config_bool(var, value);
696 return 0;
698 if (!strcmp(var, "blame.showemail")) {
699 int *output_option = cb;
700 if (git_config_bool(var, value))
701 *output_option |= OUTPUT_SHOW_EMAIL;
702 else
703 *output_option &= ~OUTPUT_SHOW_EMAIL;
704 return 0;
706 if (!strcmp(var, "blame.date")) {
707 if (!value)
708 return config_error_nonbool(var);
709 parse_date_format(value, &blame_date_mode);
710 return 0;
712 if (!strcmp(var, "blame.ignorerevsfile")) {
713 const char *str;
714 int ret;
716 ret = git_config_pathname(&str, var, value);
717 if (ret)
718 return ret;
719 string_list_insert(&ignore_revs_file_list, str);
720 return 0;
722 if (!strcmp(var, "blame.markunblamablelines")) {
723 mark_unblamable_lines = git_config_bool(var, value);
724 return 0;
726 if (!strcmp(var, "blame.markignoredlines")) {
727 mark_ignored_lines = git_config_bool(var, value);
728 return 0;
730 if (!strcmp(var, "color.blame.repeatedlines")) {
731 if (color_parse_mem(value, strlen(value), repeated_meta_color))
732 warning(_("invalid value for '%s': '%s'"),
733 "color.blame.repeatedLines", value);
734 return 0;
736 if (!strcmp(var, "color.blame.highlightrecent")) {
737 parse_color_fields(value);
738 return 0;
741 if (!strcmp(var, "blame.coloring")) {
742 if (!strcmp(value, "repeatedLines")) {
743 coloring_mode |= OUTPUT_COLOR_LINE;
744 } else if (!strcmp(value, "highlightRecent")) {
745 coloring_mode |= OUTPUT_SHOW_AGE_WITH_COLOR;
746 } else if (!strcmp(value, "none")) {
747 coloring_mode &= ~(OUTPUT_COLOR_LINE |
748 OUTPUT_SHOW_AGE_WITH_COLOR);
749 } else {
750 warning(_("invalid value for '%s': '%s'"),
751 "blame.coloring", value);
752 return 0;
756 if (git_diff_heuristic_config(var, value, cb) < 0)
757 return -1;
758 if (userdiff_config(var, value) < 0)
759 return -1;
761 return git_default_config(var, value, cb);
764 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
766 int *opt = option->value;
768 BUG_ON_OPT_NEG(unset);
771 * -C enables copy from removed files;
772 * -C -C enables copy from existing files, but only
773 * when blaming a new file;
774 * -C -C -C enables copy from existing files for
775 * everybody
777 if (*opt & PICKAXE_BLAME_COPY_HARDER)
778 *opt |= PICKAXE_BLAME_COPY_HARDEST;
779 if (*opt & PICKAXE_BLAME_COPY)
780 *opt |= PICKAXE_BLAME_COPY_HARDER;
781 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
783 if (arg)
784 blame_copy_score = parse_score(arg);
785 return 0;
788 static int blame_move_callback(const struct option *option, const char *arg, int unset)
790 int *opt = option->value;
792 BUG_ON_OPT_NEG(unset);
794 *opt |= PICKAXE_BLAME_MOVE;
796 if (arg)
797 blame_move_score = parse_score(arg);
798 return 0;
801 static int is_a_rev(const char *name)
803 struct object_id oid;
805 if (get_oid(name, &oid))
806 return 0;
807 return OBJ_NONE < oid_object_info(the_repository, &oid, NULL);
810 static int peel_to_commit_oid(struct object_id *oid_ret, void *cbdata)
812 struct repository *r = ((struct blame_scoreboard *)cbdata)->repo;
813 struct object_id oid;
815 oidcpy(&oid, oid_ret);
816 while (1) {
817 struct object *obj;
818 int kind = oid_object_info(r, &oid, NULL);
819 if (kind == OBJ_COMMIT) {
820 oidcpy(oid_ret, &oid);
821 return 0;
823 if (kind != OBJ_TAG)
824 return -1;
825 obj = deref_tag(r, parse_object(r, &oid), NULL, 0);
826 if (!obj)
827 return -1;
828 oidcpy(&oid, &obj->oid);
832 static void build_ignorelist(struct blame_scoreboard *sb,
833 struct string_list *ignore_revs_file_list,
834 struct string_list *ignore_rev_list)
836 struct string_list_item *i;
837 struct object_id oid;
839 oidset_init(&sb->ignore_list, 0);
840 for_each_string_list_item(i, ignore_revs_file_list) {
841 if (!strcmp(i->string, ""))
842 oidset_clear(&sb->ignore_list);
843 else
844 oidset_parse_file_carefully(&sb->ignore_list, i->string,
845 peel_to_commit_oid, sb);
847 for_each_string_list_item(i, ignore_rev_list) {
848 if (get_oid_committish(i->string, &oid) ||
849 peel_to_commit_oid(&oid, sb))
850 die(_("cannot find revision %s to ignore"), i->string);
851 oidset_insert(&sb->ignore_list, &oid);
855 int cmd_blame(int argc, const char **argv, const char *prefix)
857 struct rev_info revs;
858 const char *path;
859 struct blame_scoreboard sb;
860 struct blame_origin *o;
861 struct blame_entry *ent = NULL;
862 long dashdash_pos, lno;
863 struct progress_info pi = { NULL, 0 };
865 struct string_list range_list = STRING_LIST_INIT_NODUP;
866 struct string_list ignore_rev_list = STRING_LIST_INIT_NODUP;
867 int output_option = 0, opt = 0;
868 int show_stats = 0;
869 const char *revs_file = NULL;
870 const char *contents_from = NULL;
871 const struct option options[] = {
872 OPT_BOOL(0, "incremental", &incremental, N_("show blame entries as we find them, incrementally")),
873 OPT_BOOL('b', NULL, &blank_boundary, N_("do not show object names of boundary commits (Default: off)")),
874 OPT_BOOL(0, "root", &show_root, N_("do not treat root commits as boundaries (Default: off)")),
875 OPT_BOOL(0, "show-stats", &show_stats, N_("show work cost statistics")),
876 OPT_BOOL(0, "progress", &show_progress, N_("force progress reporting")),
877 OPT_BIT(0, "score-debug", &output_option, N_("show output score for blame entries"), OUTPUT_SHOW_SCORE),
878 OPT_BIT('f', "show-name", &output_option, N_("show original filename (Default: auto)"), OUTPUT_SHOW_NAME),
879 OPT_BIT('n', "show-number", &output_option, N_("show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),
880 OPT_BIT('p', "porcelain", &output_option, N_("show in a format designed for machine consumption"), OUTPUT_PORCELAIN),
881 OPT_BIT(0, "line-porcelain", &output_option, N_("show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),
882 OPT_BIT('c', NULL, &output_option, N_("use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),
883 OPT_BIT('t', NULL, &output_option, N_("show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),
884 OPT_BIT('l', NULL, &output_option, N_("show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),
885 OPT_BIT('s', NULL, &output_option, N_("suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),
886 OPT_BIT('e', "show-email", &output_option, N_("show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),
887 OPT_BIT('w', NULL, &xdl_opts, N_("ignore whitespace differences"), XDF_IGNORE_WHITESPACE),
888 OPT_STRING_LIST(0, "ignore-rev", &ignore_rev_list, N_("rev"), N_("ignore <rev> when blaming")),
889 OPT_STRING_LIST(0, "ignore-revs-file", &ignore_revs_file_list, N_("file"), N_("ignore revisions from <file>")),
890 OPT_BIT(0, "color-lines", &output_option, N_("color redundant metadata from previous line differently"), OUTPUT_COLOR_LINE),
891 OPT_BIT(0, "color-by-age", &output_option, N_("color lines by age"), OUTPUT_SHOW_AGE_WITH_COLOR),
892 OPT_BIT(0, "minimal", &xdl_opts, N_("spend extra cycles to find better match"), XDF_NEED_MINIMAL),
893 OPT_STRING('S', NULL, &revs_file, N_("file"), N_("use revisions from <file> instead of calling git-rev-list")),
894 OPT_STRING(0, "contents", &contents_from, N_("file"), N_("use <file>'s contents as the final image")),
895 OPT_CALLBACK_F('C', NULL, &opt, N_("score"), N_("find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback),
896 OPT_CALLBACK_F('M', NULL, &opt, N_("score"), N_("find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback),
897 OPT_STRING_LIST('L', NULL, &range_list, N_("range"),
898 N_("process only line range <start>,<end> or function :<funcname>")),
899 OPT__ABBREV(&abbrev),
900 OPT_END()
903 struct parse_opt_ctx_t ctx;
904 int cmd_is_annotate = !strcmp(argv[0], "annotate");
905 struct range_set ranges;
906 unsigned int range_i;
907 long anchor;
908 const int hexsz = the_hash_algo->hexsz;
909 long num_lines = 0;
910 const char *str_usage = cmd_is_annotate ? annotate_usage : blame_usage;
911 const char **opt_usage = cmd_is_annotate ? annotate_opt_usage : blame_opt_usage;
913 setup_default_color_by_age();
914 git_config(git_blame_config, &output_option);
915 repo_init_revisions(the_repository, &revs, NULL);
916 revs.date_mode = blame_date_mode;
917 revs.diffopt.flags.allow_textconv = 1;
918 revs.diffopt.flags.follow_renames = 1;
920 save_commit_buffer = 0;
921 dashdash_pos = 0;
922 show_progress = -1;
924 parse_options_start(&ctx, argc, argv, prefix, options,
925 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);
926 for (;;) {
927 switch (parse_options_step(&ctx, options, opt_usage)) {
928 case PARSE_OPT_NON_OPTION:
929 case PARSE_OPT_UNKNOWN:
930 break;
931 case PARSE_OPT_HELP:
932 case PARSE_OPT_ERROR:
933 case PARSE_OPT_SUBCOMMAND:
934 exit(129);
935 case PARSE_OPT_COMPLETE:
936 exit(0);
937 case PARSE_OPT_DONE:
938 if (ctx.argv[0])
939 dashdash_pos = ctx.cpidx;
940 goto parse_done;
943 if (!strcmp(ctx.argv[0], "--reverse")) {
944 ctx.argv[0] = "--children";
945 reverse = 1;
947 parse_revision_opt(&revs, &ctx, options, opt_usage);
949 parse_done:
950 revision_opts_finish(&revs);
951 no_whole_file_rename = !revs.diffopt.flags.follow_renames;
952 xdl_opts |= revs.diffopt.xdl_opts & XDF_INDENT_HEURISTIC;
953 revs.diffopt.flags.follow_renames = 0;
954 argc = parse_options_end(&ctx);
956 prepare_repo_settings(the_repository);
957 the_repository->settings.command_requires_full_index = 0;
959 if (incremental || (output_option & OUTPUT_PORCELAIN)) {
960 if (show_progress > 0)
961 die(_("--progress can't be used with --incremental or porcelain formats"));
962 show_progress = 0;
963 } else if (show_progress < 0)
964 show_progress = isatty(2);
966 if (0 < abbrev && abbrev < hexsz)
967 /* one more abbrev length is needed for the boundary commit */
968 abbrev++;
969 else if (!abbrev)
970 abbrev = hexsz;
972 if (revs_file && read_ancestry(revs_file))
973 die_errno("reading graft file '%s' failed", revs_file);
975 if (cmd_is_annotate) {
976 output_option |= OUTPUT_ANNOTATE_COMPAT;
977 blame_date_mode.type = DATE_ISO8601;
978 } else {
979 blame_date_mode = revs.date_mode;
982 /* The maximum width used to show the dates */
983 switch (blame_date_mode.type) {
984 case DATE_RFC2822:
985 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");
986 break;
987 case DATE_ISO8601_STRICT:
988 blame_date_width = sizeof("2006-10-19T16:00:04-07:00");
989 break;
990 case DATE_ISO8601:
991 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");
992 break;
993 case DATE_RAW:
994 blame_date_width = sizeof("1161298804 -0700");
995 break;
996 case DATE_UNIX:
997 blame_date_width = sizeof("1161298804");
998 break;
999 case DATE_SHORT:
1000 blame_date_width = sizeof("2006-10-19");
1001 break;
1002 case DATE_RELATIVE:
1004 * TRANSLATORS: This string is used to tell us the
1005 * maximum display width for a relative timestamp in
1006 * "git blame" output. For C locale, "4 years, 11
1007 * months ago", which takes 22 places, is the longest
1008 * among various forms of relative timestamps, but
1009 * your language may need more or fewer display
1010 * columns.
1012 blame_date_width = utf8_strwidth(_("4 years, 11 months ago")) + 1; /* add the null */
1013 break;
1014 case DATE_HUMAN:
1015 /* If the year is shown, no time is shown */
1016 blame_date_width = sizeof("Thu Oct 19 16:00");
1017 break;
1018 case DATE_NORMAL:
1019 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");
1020 break;
1021 case DATE_STRFTIME:
1022 blame_date_width = strlen(show_date(0, 0, &blame_date_mode)) + 1; /* add the null */
1023 break;
1025 blame_date_width -= 1; /* strip the null */
1027 if (revs.diffopt.flags.find_copies_harder)
1028 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
1029 PICKAXE_BLAME_COPY_HARDER);
1032 * We have collected options unknown to us in argv[1..unk]
1033 * which are to be passed to revision machinery if we are
1034 * going to do the "bottom" processing.
1036 * The remaining are:
1038 * (1) if dashdash_pos != 0, it is either
1039 * "blame [revisions] -- <path>" or
1040 * "blame -- <path> <rev>"
1042 * (2) otherwise, it is one of the two:
1043 * "blame [revisions] <path>"
1044 * "blame <path> <rev>"
1046 * Note that we must strip out <path> from the arguments: we do not
1047 * want the path pruning but we may want "bottom" processing.
1049 if (dashdash_pos) {
1050 switch (argc - dashdash_pos - 1) {
1051 case 2: /* (1b) */
1052 if (argc != 4)
1053 usage_with_options(opt_usage, options);
1054 /* reorder for the new way: <rev> -- <path> */
1055 argv[1] = argv[3];
1056 argv[3] = argv[2];
1057 argv[2] = "--";
1058 /* FALLTHROUGH */
1059 case 1: /* (1a) */
1060 path = add_prefix(prefix, argv[--argc]);
1061 argv[argc] = NULL;
1062 break;
1063 default:
1064 usage_with_options(opt_usage, options);
1066 } else {
1067 if (argc < 2)
1068 usage_with_options(opt_usage, options);
1069 if (argc == 3 && is_a_rev(argv[argc - 1])) { /* (2b) */
1070 path = add_prefix(prefix, argv[1]);
1071 argv[1] = argv[2];
1072 } else { /* (2a) */
1073 if (argc == 2 && is_a_rev(argv[1]) && !get_git_work_tree())
1074 die("missing <path> to blame");
1075 path = add_prefix(prefix, argv[argc - 1]);
1077 argv[argc - 1] = "--";
1080 revs.disable_stdin = 1;
1081 setup_revisions(argc, argv, &revs, NULL);
1082 if (!revs.pending.nr && is_bare_repository()) {
1083 struct commit *head_commit;
1084 struct object_id head_oid;
1086 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
1087 &head_oid, NULL) ||
1088 !(head_commit = lookup_commit_reference_gently(revs.repo,
1089 &head_oid, 1)))
1090 die("no such ref: HEAD");
1092 add_pending_object(&revs, &head_commit->object, "HEAD");
1095 init_scoreboard(&sb);
1096 sb.revs = &revs;
1097 sb.contents_from = contents_from;
1098 sb.reverse = reverse;
1099 sb.repo = the_repository;
1100 sb.path = path;
1101 build_ignorelist(&sb, &ignore_revs_file_list, &ignore_rev_list);
1102 string_list_clear(&ignore_revs_file_list, 0);
1103 string_list_clear(&ignore_rev_list, 0);
1104 setup_scoreboard(&sb, &o);
1107 * Changed-path Bloom filters are disabled when looking
1108 * for copies.
1110 if (!(opt & PICKAXE_BLAME_COPY))
1111 setup_blame_bloom_data(&sb);
1113 lno = sb.num_lines;
1115 if (lno && !range_list.nr)
1116 string_list_append(&range_list, "1");
1118 anchor = 1;
1119 range_set_init(&ranges, range_list.nr);
1120 for (range_i = 0; range_i < range_list.nr; ++range_i) {
1121 long bottom, top;
1122 if (parse_range_arg(range_list.items[range_i].string,
1123 nth_line_cb, &sb, lno, anchor,
1124 &bottom, &top, sb.path,
1125 the_repository->index))
1126 usage(str_usage);
1127 if ((!lno && (top || bottom)) || lno < bottom)
1128 die(Q_("file %s has only %lu line",
1129 "file %s has only %lu lines",
1130 lno), sb.path, lno);
1131 if (bottom < 1)
1132 bottom = 1;
1133 if (top < 1 || lno < top)
1134 top = lno;
1135 bottom--;
1136 range_set_append_unsafe(&ranges, bottom, top);
1137 anchor = top + 1;
1139 sort_and_merge_range_set(&ranges);
1141 for (range_i = ranges.nr; range_i > 0; --range_i) {
1142 const struct range *r = &ranges.ranges[range_i - 1];
1143 ent = blame_entry_prepend(ent, r->start, r->end, o);
1144 num_lines += (r->end - r->start);
1146 if (!num_lines)
1147 num_lines = sb.num_lines;
1149 o->suspects = ent;
1150 prio_queue_put(&sb.commits, o->commit);
1152 blame_origin_decref(o);
1154 range_set_release(&ranges);
1155 string_list_clear(&range_list, 0);
1157 sb.ent = NULL;
1159 if (blame_move_score)
1160 sb.move_score = blame_move_score;
1161 if (blame_copy_score)
1162 sb.copy_score = blame_copy_score;
1164 sb.debug = DEBUG_BLAME;
1165 sb.on_sanity_fail = &sanity_check_on_fail;
1167 sb.show_root = show_root;
1168 sb.xdl_opts = xdl_opts;
1169 sb.no_whole_file_rename = no_whole_file_rename;
1171 read_mailmap(&mailmap);
1173 sb.found_guilty_entry = &found_guilty_entry;
1174 sb.found_guilty_entry_data = &pi;
1175 if (show_progress)
1176 pi.progress = start_delayed_progress(_("Blaming lines"), num_lines);
1178 assign_blame(&sb, opt);
1180 stop_progress(&pi.progress);
1182 if (!incremental)
1183 setup_pager();
1184 else
1185 goto cleanup;
1187 blame_sort_final(&sb);
1189 blame_coalesce(&sb);
1191 if (!(output_option & (OUTPUT_COLOR_LINE | OUTPUT_SHOW_AGE_WITH_COLOR)))
1192 output_option |= coloring_mode;
1194 if (!(output_option & OUTPUT_PORCELAIN)) {
1195 find_alignment(&sb, &output_option);
1196 if (!*repeated_meta_color &&
1197 (output_option & OUTPUT_COLOR_LINE))
1198 xsnprintf(repeated_meta_color,
1199 sizeof(repeated_meta_color),
1200 "%s", GIT_COLOR_CYAN);
1202 if (output_option & OUTPUT_ANNOTATE_COMPAT)
1203 output_option &= ~(OUTPUT_COLOR_LINE | OUTPUT_SHOW_AGE_WITH_COLOR);
1205 output(&sb, output_option);
1206 free((void *)sb.final_buf);
1207 for (ent = sb.ent; ent; ) {
1208 struct blame_entry *e = ent->next;
1209 free(ent);
1210 ent = e;
1213 if (show_stats) {
1214 printf("num read blob: %d\n", sb.num_read_blob);
1215 printf("num get patch: %d\n", sb.num_get_patch);
1216 printf("num commits: %d\n", sb.num_commits);
1219 cleanup:
1220 cleanup_scoreboard(&sb);
1221 release_revisions(&revs);
1222 return 0;