setup.h: move declarations for setup.c functions from cache.h
[git.git] / builtin / blame.c
blobfb271bae70ef03340ea4e384baf0215680e6bcd1
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-store.h"
32 #include "blame.h"
33 #include "refs.h"
34 #include "setup.h"
35 #include "tag.h"
37 static char blame_usage[] = N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>");
38 static char annotate_usage[] = N_("git annotate [<options>] [<rev-opts>] [<rev>] [--] <file>");
40 static const char *blame_opt_usage[] = {
41 blame_usage,
42 "",
43 N_("<rev-opts> are documented in git-rev-list(1)"),
44 NULL
47 static const char *annotate_opt_usage[] = {
48 annotate_usage,
49 "",
50 N_("<rev-opts> are documented in git-rev-list(1)"),
51 NULL
54 static int longest_file;
55 static int longest_author;
56 static int max_orig_digits;
57 static int max_digits;
58 static int max_score_digits;
59 static int show_root;
60 static int reverse;
61 static int blank_boundary;
62 static int incremental;
63 static int xdl_opts;
64 static int abbrev = -1;
65 static int no_whole_file_rename;
66 static int show_progress;
67 static char repeated_meta_color[COLOR_MAXLEN];
68 static int coloring_mode;
69 static struct string_list ignore_revs_file_list = STRING_LIST_INIT_NODUP;
70 static int mark_unblamable_lines;
71 static int mark_ignored_lines;
73 static struct date_mode blame_date_mode = { DATE_ISO8601 };
74 static size_t blame_date_width;
76 static struct string_list mailmap = STRING_LIST_INIT_NODUP;
78 #ifndef DEBUG_BLAME
79 #define DEBUG_BLAME 0
80 #endif
82 static unsigned blame_move_score;
83 static unsigned blame_copy_score;
85 /* Remember to update object flag allocation in object.h */
86 #define METAINFO_SHOWN (1u<<12)
87 #define MORE_THAN_ONE_PATH (1u<<13)
89 struct progress_info {
90 struct progress *progress;
91 int blamed_lines;
94 static const char *nth_line_cb(void *data, long lno)
96 return blame_nth_line((struct blame_scoreboard *)data, lno);
100 * Information on commits, used for output.
102 struct commit_info {
103 struct strbuf author;
104 struct strbuf author_mail;
105 timestamp_t author_time;
106 struct strbuf author_tz;
108 /* filled only when asked for details */
109 struct strbuf committer;
110 struct strbuf committer_mail;
111 timestamp_t committer_time;
112 struct strbuf committer_tz;
114 struct strbuf summary;
117 #define COMMIT_INFO_INIT { \
118 .author = STRBUF_INIT, \
119 .author_mail = STRBUF_INIT, \
120 .author_tz = STRBUF_INIT, \
121 .committer = STRBUF_INIT, \
122 .committer_mail = STRBUF_INIT, \
123 .committer_tz = STRBUF_INIT, \
124 .summary = STRBUF_INIT, \
128 * Parse author/committer line in the commit object buffer
130 static void get_ac_line(const char *inbuf, const char *what,
131 struct strbuf *name, struct strbuf *mail,
132 timestamp_t *time, struct strbuf *tz)
134 struct ident_split ident;
135 size_t len, maillen, namelen;
136 char *tmp, *endp;
137 const char *namebuf, *mailbuf;
139 tmp = strstr(inbuf, what);
140 if (!tmp)
141 goto error_out;
142 tmp += strlen(what);
143 endp = strchr(tmp, '\n');
144 if (!endp)
145 len = strlen(tmp);
146 else
147 len = endp - tmp;
149 if (split_ident_line(&ident, tmp, len)) {
150 error_out:
151 /* Ugh */
152 tmp = "(unknown)";
153 strbuf_addstr(name, tmp);
154 strbuf_addstr(mail, tmp);
155 strbuf_addstr(tz, tmp);
156 *time = 0;
157 return;
160 namelen = ident.name_end - ident.name_begin;
161 namebuf = ident.name_begin;
163 maillen = ident.mail_end - ident.mail_begin;
164 mailbuf = ident.mail_begin;
166 if (ident.date_begin && ident.date_end)
167 *time = strtoul(ident.date_begin, NULL, 10);
168 else
169 *time = 0;
171 if (ident.tz_begin && ident.tz_end)
172 strbuf_add(tz, ident.tz_begin, ident.tz_end - ident.tz_begin);
173 else
174 strbuf_addstr(tz, "(unknown)");
177 * Now, convert both name and e-mail using mailmap
179 map_user(&mailmap, &mailbuf, &maillen,
180 &namebuf, &namelen);
182 strbuf_addf(mail, "<%.*s>", (int)maillen, mailbuf);
183 strbuf_add(name, namebuf, namelen);
186 static void commit_info_destroy(struct commit_info *ci)
189 strbuf_release(&ci->author);
190 strbuf_release(&ci->author_mail);
191 strbuf_release(&ci->author_tz);
192 strbuf_release(&ci->committer);
193 strbuf_release(&ci->committer_mail);
194 strbuf_release(&ci->committer_tz);
195 strbuf_release(&ci->summary);
198 static void get_commit_info(struct commit *commit,
199 struct commit_info *ret,
200 int detailed)
202 int len;
203 const char *subject, *encoding;
204 const char *message;
206 encoding = get_log_output_encoding();
207 message = logmsg_reencode(commit, NULL, encoding);
208 get_ac_line(message, "\nauthor ",
209 &ret->author, &ret->author_mail,
210 &ret->author_time, &ret->author_tz);
212 if (!detailed) {
213 unuse_commit_buffer(commit, message);
214 return;
217 get_ac_line(message, "\ncommitter ",
218 &ret->committer, &ret->committer_mail,
219 &ret->committer_time, &ret->committer_tz);
221 len = find_commit_subject(message, &subject);
222 if (len)
223 strbuf_add(&ret->summary, subject, len);
224 else
225 strbuf_addf(&ret->summary, "(%s)", oid_to_hex(&commit->object.oid));
227 unuse_commit_buffer(commit, message);
231 * Write out any suspect information which depends on the path. This must be
232 * handled separately from emit_one_suspect_detail(), because a given commit
233 * may have changes in multiple paths. So this needs to appear each time
234 * we mention a new group.
236 * To allow LF and other nonportable characters in pathnames,
237 * they are c-style quoted as needed.
239 static void write_filename_info(struct blame_origin *suspect)
241 if (suspect->previous) {
242 struct blame_origin *prev = suspect->previous;
243 printf("previous %s ", oid_to_hex(&prev->commit->object.oid));
244 write_name_quoted(prev->path, stdout, '\n');
246 printf("filename ");
247 write_name_quoted(suspect->path, stdout, '\n');
251 * Porcelain/Incremental format wants to show a lot of details per
252 * commit. Instead of repeating this every line, emit it only once,
253 * the first time each commit appears in the output (unless the
254 * user has specifically asked for us to repeat).
256 static int emit_one_suspect_detail(struct blame_origin *suspect, int repeat)
258 struct commit_info ci = COMMIT_INFO_INIT;
260 if (!repeat && (suspect->commit->object.flags & METAINFO_SHOWN))
261 return 0;
263 suspect->commit->object.flags |= METAINFO_SHOWN;
264 get_commit_info(suspect->commit, &ci, 1);
265 printf("author %s\n", ci.author.buf);
266 printf("author-mail %s\n", ci.author_mail.buf);
267 printf("author-time %"PRItime"\n", ci.author_time);
268 printf("author-tz %s\n", ci.author_tz.buf);
269 printf("committer %s\n", ci.committer.buf);
270 printf("committer-mail %s\n", ci.committer_mail.buf);
271 printf("committer-time %"PRItime"\n", ci.committer_time);
272 printf("committer-tz %s\n", ci.committer_tz.buf);
273 printf("summary %s\n", ci.summary.buf);
274 if (suspect->commit->object.flags & UNINTERESTING)
275 printf("boundary\n");
277 commit_info_destroy(&ci);
279 return 1;
283 * The blame_entry is found to be guilty for the range.
284 * Show it in incremental output.
286 static void found_guilty_entry(struct blame_entry *ent, void *data)
288 struct progress_info *pi = (struct progress_info *)data;
290 if (incremental) {
291 struct blame_origin *suspect = ent->suspect;
293 printf("%s %d %d %d\n",
294 oid_to_hex(&suspect->commit->object.oid),
295 ent->s_lno + 1, ent->lno + 1, ent->num_lines);
296 emit_one_suspect_detail(suspect, 0);
297 write_filename_info(suspect);
298 maybe_flush_or_die(stdout, "stdout");
300 pi->blamed_lines += ent->num_lines;
301 display_progress(pi->progress, pi->blamed_lines);
304 static const char *format_time(timestamp_t time, const char *tz_str,
305 int show_raw_time)
307 static struct strbuf time_buf = STRBUF_INIT;
309 strbuf_reset(&time_buf);
310 if (show_raw_time) {
311 strbuf_addf(&time_buf, "%"PRItime" %s", time, tz_str);
313 else {
314 const char *time_str;
315 size_t time_width;
316 int tz;
317 tz = atoi(tz_str);
318 time_str = show_date(time, tz, &blame_date_mode);
319 strbuf_addstr(&time_buf, time_str);
321 * Add space paddings to time_buf to display a fixed width
322 * string, and use time_width for display width calibration.
324 for (time_width = utf8_strwidth(time_str);
325 time_width < blame_date_width;
326 time_width++)
327 strbuf_addch(&time_buf, ' ');
329 return time_buf.buf;
332 #define OUTPUT_ANNOTATE_COMPAT (1U<<0)
333 #define OUTPUT_LONG_OBJECT_NAME (1U<<1)
334 #define OUTPUT_RAW_TIMESTAMP (1U<<2)
335 #define OUTPUT_PORCELAIN (1U<<3)
336 #define OUTPUT_SHOW_NAME (1U<<4)
337 #define OUTPUT_SHOW_NUMBER (1U<<5)
338 #define OUTPUT_SHOW_SCORE (1U<<6)
339 #define OUTPUT_NO_AUTHOR (1U<<7)
340 #define OUTPUT_SHOW_EMAIL (1U<<8)
341 #define OUTPUT_LINE_PORCELAIN (1U<<9)
342 #define OUTPUT_COLOR_LINE (1U<<10)
343 #define OUTPUT_SHOW_AGE_WITH_COLOR (1U<<11)
345 static void emit_porcelain_details(struct blame_origin *suspect, int repeat)
347 if (emit_one_suspect_detail(suspect, repeat) ||
348 (suspect->commit->object.flags & MORE_THAN_ONE_PATH))
349 write_filename_info(suspect);
352 static void emit_porcelain(struct blame_scoreboard *sb, struct blame_entry *ent,
353 int opt)
355 int repeat = opt & OUTPUT_LINE_PORCELAIN;
356 int cnt;
357 const char *cp;
358 struct blame_origin *suspect = ent->suspect;
359 char hex[GIT_MAX_HEXSZ + 1];
361 oid_to_hex_r(hex, &suspect->commit->object.oid);
362 printf("%s %d %d %d\n",
363 hex,
364 ent->s_lno + 1,
365 ent->lno + 1,
366 ent->num_lines);
367 emit_porcelain_details(suspect, repeat);
369 cp = blame_nth_line(sb, ent->lno);
370 for (cnt = 0; cnt < ent->num_lines; cnt++) {
371 char ch;
372 if (cnt) {
373 printf("%s %d %d\n", hex,
374 ent->s_lno + 1 + cnt,
375 ent->lno + 1 + cnt);
376 if (repeat)
377 emit_porcelain_details(suspect, 1);
379 putchar('\t');
380 do {
381 ch = *cp++;
382 putchar(ch);
383 } while (ch != '\n' &&
384 cp < sb->final_buf + sb->final_buf_size);
387 if (sb->final_buf_size && cp[-1] != '\n')
388 putchar('\n');
391 static struct color_field {
392 timestamp_t hop;
393 char col[COLOR_MAXLEN];
394 } *colorfield;
395 static int colorfield_nr, colorfield_alloc;
397 static void parse_color_fields(const char *s)
399 struct string_list l = STRING_LIST_INIT_DUP;
400 struct string_list_item *item;
401 enum { EXPECT_DATE, EXPECT_COLOR } next = EXPECT_COLOR;
403 colorfield_nr = 0;
405 /* Ideally this would be stripped and split at the same time? */
406 string_list_split(&l, s, ',', -1);
407 ALLOC_GROW(colorfield, colorfield_nr + 1, colorfield_alloc);
409 for_each_string_list_item(item, &l) {
410 switch (next) {
411 case EXPECT_DATE:
412 colorfield[colorfield_nr].hop = approxidate(item->string);
413 next = EXPECT_COLOR;
414 colorfield_nr++;
415 ALLOC_GROW(colorfield, colorfield_nr + 1, colorfield_alloc);
416 break;
417 case EXPECT_COLOR:
418 if (color_parse(item->string, colorfield[colorfield_nr].col))
419 die(_("expecting a color: %s"), item->string);
420 next = EXPECT_DATE;
421 break;
425 if (next == EXPECT_COLOR)
426 die(_("must end with a color"));
428 colorfield[colorfield_nr].hop = TIME_MAX;
429 string_list_clear(&l, 0);
432 static void setup_default_color_by_age(void)
434 parse_color_fields("blue,12 month ago,white,1 month ago,red");
437 static void determine_line_heat(struct commit_info *ci, const char **dest_color)
439 int i = 0;
441 while (i < colorfield_nr && ci->author_time > colorfield[i].hop)
442 i++;
444 *dest_color = colorfield[i].col;
447 static void emit_other(struct blame_scoreboard *sb, struct blame_entry *ent, int opt)
449 int cnt;
450 const char *cp;
451 struct blame_origin *suspect = ent->suspect;
452 struct commit_info ci = COMMIT_INFO_INIT;
453 char hex[GIT_MAX_HEXSZ + 1];
454 int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
455 const char *default_color = NULL, *color = NULL, *reset = NULL;
457 get_commit_info(suspect->commit, &ci, 1);
458 oid_to_hex_r(hex, &suspect->commit->object.oid);
460 cp = blame_nth_line(sb, ent->lno);
462 if (opt & OUTPUT_SHOW_AGE_WITH_COLOR) {
463 determine_line_heat(&ci, &default_color);
464 color = default_color;
465 reset = GIT_COLOR_RESET;
468 for (cnt = 0; cnt < ent->num_lines; cnt++) {
469 char ch;
470 int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? the_hash_algo->hexsz : abbrev;
472 if (opt & OUTPUT_COLOR_LINE) {
473 if (cnt > 0) {
474 color = repeated_meta_color;
475 reset = GIT_COLOR_RESET;
476 } else {
477 color = default_color ? default_color : NULL;
478 reset = default_color ? GIT_COLOR_RESET : NULL;
481 if (color)
482 fputs(color, stdout);
484 if (suspect->commit->object.flags & UNINTERESTING) {
485 if (blank_boundary)
486 memset(hex, ' ', length);
487 else if (!(opt & OUTPUT_ANNOTATE_COMPAT)) {
488 length--;
489 putchar('^');
493 if (mark_unblamable_lines && ent->unblamable) {
494 length--;
495 putchar('*');
497 if (mark_ignored_lines && ent->ignored) {
498 length--;
499 putchar('?');
501 printf("%.*s", length, hex);
502 if (opt & OUTPUT_ANNOTATE_COMPAT) {
503 const char *name;
504 if (opt & OUTPUT_SHOW_EMAIL)
505 name = ci.author_mail.buf;
506 else
507 name = ci.author.buf;
508 printf("\t(%10s\t%10s\t%d)", name,
509 format_time(ci.author_time, ci.author_tz.buf,
510 show_raw_time),
511 ent->lno + 1 + cnt);
512 } else {
513 if (opt & OUTPUT_SHOW_SCORE)
514 printf(" %*d %02d",
515 max_score_digits, ent->score,
516 ent->suspect->refcnt);
517 if (opt & OUTPUT_SHOW_NAME)
518 printf(" %-*.*s", longest_file, longest_file,
519 suspect->path);
520 if (opt & OUTPUT_SHOW_NUMBER)
521 printf(" %*d", max_orig_digits,
522 ent->s_lno + 1 + cnt);
524 if (!(opt & OUTPUT_NO_AUTHOR)) {
525 const char *name;
526 int pad;
527 if (opt & OUTPUT_SHOW_EMAIL)
528 name = ci.author_mail.buf;
529 else
530 name = ci.author.buf;
531 pad = longest_author - utf8_strwidth(name);
532 printf(" (%s%*s %10s",
533 name, pad, "",
534 format_time(ci.author_time,
535 ci.author_tz.buf,
536 show_raw_time));
538 printf(" %*d) ",
539 max_digits, ent->lno + 1 + cnt);
541 if (reset)
542 fputs(reset, stdout);
543 do {
544 ch = *cp++;
545 putchar(ch);
546 } while (ch != '\n' &&
547 cp < sb->final_buf + sb->final_buf_size);
550 if (sb->final_buf_size && cp[-1] != '\n')
551 putchar('\n');
553 commit_info_destroy(&ci);
556 static void output(struct blame_scoreboard *sb, int option)
558 struct blame_entry *ent;
560 if (option & OUTPUT_PORCELAIN) {
561 for (ent = sb->ent; ent; ent = ent->next) {
562 int count = 0;
563 struct blame_origin *suspect;
564 struct commit *commit = ent->suspect->commit;
565 if (commit->object.flags & MORE_THAN_ONE_PATH)
566 continue;
567 for (suspect = get_blame_suspects(commit); suspect; suspect = suspect->next) {
568 if (suspect->guilty && count++) {
569 commit->object.flags |= MORE_THAN_ONE_PATH;
570 break;
576 for (ent = sb->ent; ent; ent = ent->next) {
577 if (option & OUTPUT_PORCELAIN)
578 emit_porcelain(sb, ent, option);
579 else {
580 emit_other(sb, ent, option);
586 * Add phony grafts for use with -S; this is primarily to
587 * support git's cvsserver that wants to give a linear history
588 * to its clients.
590 static int read_ancestry(const char *graft_file)
592 FILE *fp = fopen_or_warn(graft_file, "r");
593 struct strbuf buf = STRBUF_INIT;
594 if (!fp)
595 return -1;
596 while (!strbuf_getwholeline(&buf, fp, '\n')) {
597 /* The format is just "Commit Parent1 Parent2 ...\n" */
598 struct commit_graft *graft = read_graft_line(&buf);
599 if (graft)
600 register_commit_graft(the_repository, graft, 0);
602 fclose(fp);
603 strbuf_release(&buf);
604 return 0;
607 static int update_auto_abbrev(int auto_abbrev, struct blame_origin *suspect)
609 const char *uniq = find_unique_abbrev(&suspect->commit->object.oid,
610 auto_abbrev);
611 int len = strlen(uniq);
612 if (auto_abbrev < len)
613 return len;
614 return auto_abbrev;
618 * How many columns do we need to show line numbers, authors,
619 * and filenames?
621 static void find_alignment(struct blame_scoreboard *sb, int *option)
623 int longest_src_lines = 0;
624 int longest_dst_lines = 0;
625 unsigned largest_score = 0;
626 struct blame_entry *e;
627 int compute_auto_abbrev = (abbrev < 0);
628 int auto_abbrev = DEFAULT_ABBREV;
630 for (e = sb->ent; e; e = e->next) {
631 struct blame_origin *suspect = e->suspect;
632 int num;
634 if (compute_auto_abbrev)
635 auto_abbrev = update_auto_abbrev(auto_abbrev, suspect);
636 if (strcmp(suspect->path, sb->path))
637 *option |= OUTPUT_SHOW_NAME;
638 num = strlen(suspect->path);
639 if (longest_file < num)
640 longest_file = num;
641 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
642 struct commit_info ci = COMMIT_INFO_INIT;
643 suspect->commit->object.flags |= METAINFO_SHOWN;
644 get_commit_info(suspect->commit, &ci, 1);
645 if (*option & OUTPUT_SHOW_EMAIL)
646 num = utf8_strwidth(ci.author_mail.buf);
647 else
648 num = utf8_strwidth(ci.author.buf);
649 if (longest_author < num)
650 longest_author = num;
651 commit_info_destroy(&ci);
653 num = e->s_lno + e->num_lines;
654 if (longest_src_lines < num)
655 longest_src_lines = num;
656 num = e->lno + e->num_lines;
657 if (longest_dst_lines < num)
658 longest_dst_lines = num;
659 if (largest_score < blame_entry_score(sb, e))
660 largest_score = blame_entry_score(sb, e);
662 max_orig_digits = decimal_width(longest_src_lines);
663 max_digits = decimal_width(longest_dst_lines);
664 max_score_digits = decimal_width(largest_score);
666 if (compute_auto_abbrev)
667 /* one more abbrev length is needed for the boundary commit */
668 abbrev = auto_abbrev + 1;
671 static void sanity_check_on_fail(struct blame_scoreboard *sb, int baa)
673 int opt = OUTPUT_SHOW_SCORE | OUTPUT_SHOW_NUMBER | OUTPUT_SHOW_NAME;
674 find_alignment(sb, &opt);
675 output(sb, opt);
676 die("Baa %d!", baa);
679 static unsigned parse_score(const char *arg)
681 char *end;
682 unsigned long score = strtoul(arg, &end, 10);
683 if (*end)
684 return 0;
685 return score;
688 static const char *add_prefix(const char *prefix, const char *path)
690 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
693 static int git_blame_config(const char *var, const char *value, void *cb)
695 if (!strcmp(var, "blame.showroot")) {
696 show_root = git_config_bool(var, value);
697 return 0;
699 if (!strcmp(var, "blame.blankboundary")) {
700 blank_boundary = git_config_bool(var, value);
701 return 0;
703 if (!strcmp(var, "blame.showemail")) {
704 int *output_option = cb;
705 if (git_config_bool(var, value))
706 *output_option |= OUTPUT_SHOW_EMAIL;
707 else
708 *output_option &= ~OUTPUT_SHOW_EMAIL;
709 return 0;
711 if (!strcmp(var, "blame.date")) {
712 if (!value)
713 return config_error_nonbool(var);
714 parse_date_format(value, &blame_date_mode);
715 return 0;
717 if (!strcmp(var, "blame.ignorerevsfile")) {
718 const char *str;
719 int ret;
721 ret = git_config_pathname(&str, var, value);
722 if (ret)
723 return ret;
724 string_list_insert(&ignore_revs_file_list, str);
725 return 0;
727 if (!strcmp(var, "blame.markunblamablelines")) {
728 mark_unblamable_lines = git_config_bool(var, value);
729 return 0;
731 if (!strcmp(var, "blame.markignoredlines")) {
732 mark_ignored_lines = git_config_bool(var, value);
733 return 0;
735 if (!strcmp(var, "color.blame.repeatedlines")) {
736 if (color_parse_mem(value, strlen(value), repeated_meta_color))
737 warning(_("invalid value for '%s': '%s'"),
738 "color.blame.repeatedLines", value);
739 return 0;
741 if (!strcmp(var, "color.blame.highlightrecent")) {
742 parse_color_fields(value);
743 return 0;
746 if (!strcmp(var, "blame.coloring")) {
747 if (!strcmp(value, "repeatedLines")) {
748 coloring_mode |= OUTPUT_COLOR_LINE;
749 } else if (!strcmp(value, "highlightRecent")) {
750 coloring_mode |= OUTPUT_SHOW_AGE_WITH_COLOR;
751 } else if (!strcmp(value, "none")) {
752 coloring_mode &= ~(OUTPUT_COLOR_LINE |
753 OUTPUT_SHOW_AGE_WITH_COLOR);
754 } else {
755 warning(_("invalid value for '%s': '%s'"),
756 "blame.coloring", value);
757 return 0;
761 if (git_diff_heuristic_config(var, value, cb) < 0)
762 return -1;
763 if (userdiff_config(var, value) < 0)
764 return -1;
766 return git_default_config(var, value, cb);
769 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
771 int *opt = option->value;
773 BUG_ON_OPT_NEG(unset);
776 * -C enables copy from removed files;
777 * -C -C enables copy from existing files, but only
778 * when blaming a new file;
779 * -C -C -C enables copy from existing files for
780 * everybody
782 if (*opt & PICKAXE_BLAME_COPY_HARDER)
783 *opt |= PICKAXE_BLAME_COPY_HARDEST;
784 if (*opt & PICKAXE_BLAME_COPY)
785 *opt |= PICKAXE_BLAME_COPY_HARDER;
786 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
788 if (arg)
789 blame_copy_score = parse_score(arg);
790 return 0;
793 static int blame_move_callback(const struct option *option, const char *arg, int unset)
795 int *opt = option->value;
797 BUG_ON_OPT_NEG(unset);
799 *opt |= PICKAXE_BLAME_MOVE;
801 if (arg)
802 blame_move_score = parse_score(arg);
803 return 0;
806 static int is_a_rev(const char *name)
808 struct object_id oid;
810 if (get_oid(name, &oid))
811 return 0;
812 return OBJ_NONE < oid_object_info(the_repository, &oid, NULL);
815 static int peel_to_commit_oid(struct object_id *oid_ret, void *cbdata)
817 struct repository *r = ((struct blame_scoreboard *)cbdata)->repo;
818 struct object_id oid;
820 oidcpy(&oid, oid_ret);
821 while (1) {
822 struct object *obj;
823 int kind = oid_object_info(r, &oid, NULL);
824 if (kind == OBJ_COMMIT) {
825 oidcpy(oid_ret, &oid);
826 return 0;
828 if (kind != OBJ_TAG)
829 return -1;
830 obj = deref_tag(r, parse_object(r, &oid), NULL, 0);
831 if (!obj)
832 return -1;
833 oidcpy(&oid, &obj->oid);
837 static void build_ignorelist(struct blame_scoreboard *sb,
838 struct string_list *ignore_revs_file_list,
839 struct string_list *ignore_rev_list)
841 struct string_list_item *i;
842 struct object_id oid;
844 oidset_init(&sb->ignore_list, 0);
845 for_each_string_list_item(i, ignore_revs_file_list) {
846 if (!strcmp(i->string, ""))
847 oidset_clear(&sb->ignore_list);
848 else
849 oidset_parse_file_carefully(&sb->ignore_list, i->string,
850 peel_to_commit_oid, sb);
852 for_each_string_list_item(i, ignore_rev_list) {
853 if (get_oid_committish(i->string, &oid) ||
854 peel_to_commit_oid(&oid, sb))
855 die(_("cannot find revision %s to ignore"), i->string);
856 oidset_insert(&sb->ignore_list, &oid);
860 int cmd_blame(int argc, const char **argv, const char *prefix)
862 struct rev_info revs;
863 const char *path;
864 struct blame_scoreboard sb;
865 struct blame_origin *o;
866 struct blame_entry *ent = NULL;
867 long dashdash_pos, lno;
868 struct progress_info pi = { NULL, 0 };
870 struct string_list range_list = STRING_LIST_INIT_NODUP;
871 struct string_list ignore_rev_list = STRING_LIST_INIT_NODUP;
872 int output_option = 0, opt = 0;
873 int show_stats = 0;
874 const char *revs_file = NULL;
875 const char *contents_from = NULL;
876 const struct option options[] = {
877 OPT_BOOL(0, "incremental", &incremental, N_("show blame entries as we find them, incrementally")),
878 OPT_BOOL('b', NULL, &blank_boundary, N_("do not show object names of boundary commits (Default: off)")),
879 OPT_BOOL(0, "root", &show_root, N_("do not treat root commits as boundaries (Default: off)")),
880 OPT_BOOL(0, "show-stats", &show_stats, N_("show work cost statistics")),
881 OPT_BOOL(0, "progress", &show_progress, N_("force progress reporting")),
882 OPT_BIT(0, "score-debug", &output_option, N_("show output score for blame entries"), OUTPUT_SHOW_SCORE),
883 OPT_BIT('f', "show-name", &output_option, N_("show original filename (Default: auto)"), OUTPUT_SHOW_NAME),
884 OPT_BIT('n', "show-number", &output_option, N_("show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),
885 OPT_BIT('p', "porcelain", &output_option, N_("show in a format designed for machine consumption"), OUTPUT_PORCELAIN),
886 OPT_BIT(0, "line-porcelain", &output_option, N_("show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),
887 OPT_BIT('c', NULL, &output_option, N_("use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),
888 OPT_BIT('t', NULL, &output_option, N_("show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),
889 OPT_BIT('l', NULL, &output_option, N_("show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),
890 OPT_BIT('s', NULL, &output_option, N_("suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),
891 OPT_BIT('e', "show-email", &output_option, N_("show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),
892 OPT_BIT('w', NULL, &xdl_opts, N_("ignore whitespace differences"), XDF_IGNORE_WHITESPACE),
893 OPT_STRING_LIST(0, "ignore-rev", &ignore_rev_list, N_("rev"), N_("ignore <rev> when blaming")),
894 OPT_STRING_LIST(0, "ignore-revs-file", &ignore_revs_file_list, N_("file"), N_("ignore revisions from <file>")),
895 OPT_BIT(0, "color-lines", &output_option, N_("color redundant metadata from previous line differently"), OUTPUT_COLOR_LINE),
896 OPT_BIT(0, "color-by-age", &output_option, N_("color lines by age"), OUTPUT_SHOW_AGE_WITH_COLOR),
897 OPT_BIT(0, "minimal", &xdl_opts, N_("spend extra cycles to find better match"), XDF_NEED_MINIMAL),
898 OPT_STRING('S', NULL, &revs_file, N_("file"), N_("use revisions from <file> instead of calling git-rev-list")),
899 OPT_STRING(0, "contents", &contents_from, N_("file"), N_("use <file>'s contents as the final image")),
900 OPT_CALLBACK_F('C', NULL, &opt, N_("score"), N_("find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback),
901 OPT_CALLBACK_F('M', NULL, &opt, N_("score"), N_("find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback),
902 OPT_STRING_LIST('L', NULL, &range_list, N_("range"),
903 N_("process only line range <start>,<end> or function :<funcname>")),
904 OPT__ABBREV(&abbrev),
905 OPT_END()
908 struct parse_opt_ctx_t ctx;
909 int cmd_is_annotate = !strcmp(argv[0], "annotate");
910 struct range_set ranges;
911 unsigned int range_i;
912 long anchor;
913 const int hexsz = the_hash_algo->hexsz;
914 long num_lines = 0;
915 const char *str_usage = cmd_is_annotate ? annotate_usage : blame_usage;
916 const char **opt_usage = cmd_is_annotate ? annotate_opt_usage : blame_opt_usage;
918 setup_default_color_by_age();
919 git_config(git_blame_config, &output_option);
920 repo_init_revisions(the_repository, &revs, NULL);
921 revs.date_mode = blame_date_mode;
922 revs.diffopt.flags.allow_textconv = 1;
923 revs.diffopt.flags.follow_renames = 1;
925 save_commit_buffer = 0;
926 dashdash_pos = 0;
927 show_progress = -1;
929 parse_options_start(&ctx, argc, argv, prefix, options,
930 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);
931 for (;;) {
932 switch (parse_options_step(&ctx, options, opt_usage)) {
933 case PARSE_OPT_NON_OPTION:
934 case PARSE_OPT_UNKNOWN:
935 break;
936 case PARSE_OPT_HELP:
937 case PARSE_OPT_ERROR:
938 case PARSE_OPT_SUBCOMMAND:
939 exit(129);
940 case PARSE_OPT_COMPLETE:
941 exit(0);
942 case PARSE_OPT_DONE:
943 if (ctx.argv[0])
944 dashdash_pos = ctx.cpidx;
945 goto parse_done;
948 if (!strcmp(ctx.argv[0], "--reverse")) {
949 ctx.argv[0] = "--children";
950 reverse = 1;
952 parse_revision_opt(&revs, &ctx, options, opt_usage);
954 parse_done:
955 revision_opts_finish(&revs);
956 no_whole_file_rename = !revs.diffopt.flags.follow_renames;
957 xdl_opts |= revs.diffopt.xdl_opts & XDF_INDENT_HEURISTIC;
958 revs.diffopt.flags.follow_renames = 0;
959 argc = parse_options_end(&ctx);
961 prepare_repo_settings(the_repository);
962 the_repository->settings.command_requires_full_index = 0;
964 if (incremental || (output_option & OUTPUT_PORCELAIN)) {
965 if (show_progress > 0)
966 die(_("--progress can't be used with --incremental or porcelain formats"));
967 show_progress = 0;
968 } else if (show_progress < 0)
969 show_progress = isatty(2);
971 if (0 < abbrev && abbrev < hexsz)
972 /* one more abbrev length is needed for the boundary commit */
973 abbrev++;
974 else if (!abbrev)
975 abbrev = hexsz;
977 if (revs_file && read_ancestry(revs_file))
978 die_errno("reading graft file '%s' failed", revs_file);
980 if (cmd_is_annotate) {
981 output_option |= OUTPUT_ANNOTATE_COMPAT;
982 blame_date_mode.type = DATE_ISO8601;
983 } else {
984 blame_date_mode = revs.date_mode;
987 /* The maximum width used to show the dates */
988 switch (blame_date_mode.type) {
989 case DATE_RFC2822:
990 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");
991 break;
992 case DATE_ISO8601_STRICT:
993 blame_date_width = sizeof("2006-10-19T16:00:04-07:00");
994 break;
995 case DATE_ISO8601:
996 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");
997 break;
998 case DATE_RAW:
999 blame_date_width = sizeof("1161298804 -0700");
1000 break;
1001 case DATE_UNIX:
1002 blame_date_width = sizeof("1161298804");
1003 break;
1004 case DATE_SHORT:
1005 blame_date_width = sizeof("2006-10-19");
1006 break;
1007 case DATE_RELATIVE:
1009 * TRANSLATORS: This string is used to tell us the
1010 * maximum display width for a relative timestamp in
1011 * "git blame" output. For C locale, "4 years, 11
1012 * months ago", which takes 22 places, is the longest
1013 * among various forms of relative timestamps, but
1014 * your language may need more or fewer display
1015 * columns.
1017 blame_date_width = utf8_strwidth(_("4 years, 11 months ago")) + 1; /* add the null */
1018 break;
1019 case DATE_HUMAN:
1020 /* If the year is shown, no time is shown */
1021 blame_date_width = sizeof("Thu Oct 19 16:00");
1022 break;
1023 case DATE_NORMAL:
1024 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");
1025 break;
1026 case DATE_STRFTIME:
1027 blame_date_width = strlen(show_date(0, 0, &blame_date_mode)) + 1; /* add the null */
1028 break;
1030 blame_date_width -= 1; /* strip the null */
1032 if (revs.diffopt.flags.find_copies_harder)
1033 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
1034 PICKAXE_BLAME_COPY_HARDER);
1037 * We have collected options unknown to us in argv[1..unk]
1038 * which are to be passed to revision machinery if we are
1039 * going to do the "bottom" processing.
1041 * The remaining are:
1043 * (1) if dashdash_pos != 0, it is either
1044 * "blame [revisions] -- <path>" or
1045 * "blame -- <path> <rev>"
1047 * (2) otherwise, it is one of the two:
1048 * "blame [revisions] <path>"
1049 * "blame <path> <rev>"
1051 * Note that we must strip out <path> from the arguments: we do not
1052 * want the path pruning but we may want "bottom" processing.
1054 if (dashdash_pos) {
1055 switch (argc - dashdash_pos - 1) {
1056 case 2: /* (1b) */
1057 if (argc != 4)
1058 usage_with_options(opt_usage, options);
1059 /* reorder for the new way: <rev> -- <path> */
1060 argv[1] = argv[3];
1061 argv[3] = argv[2];
1062 argv[2] = "--";
1063 /* FALLTHROUGH */
1064 case 1: /* (1a) */
1065 path = add_prefix(prefix, argv[--argc]);
1066 argv[argc] = NULL;
1067 break;
1068 default:
1069 usage_with_options(opt_usage, options);
1071 } else {
1072 if (argc < 2)
1073 usage_with_options(opt_usage, options);
1074 if (argc == 3 && is_a_rev(argv[argc - 1])) { /* (2b) */
1075 path = add_prefix(prefix, argv[1]);
1076 argv[1] = argv[2];
1077 } else { /* (2a) */
1078 if (argc == 2 && is_a_rev(argv[1]) && !get_git_work_tree())
1079 die("missing <path> to blame");
1080 path = add_prefix(prefix, argv[argc - 1]);
1082 argv[argc - 1] = "--";
1085 revs.disable_stdin = 1;
1086 setup_revisions(argc, argv, &revs, NULL);
1087 if (!revs.pending.nr && is_bare_repository()) {
1088 struct commit *head_commit;
1089 struct object_id head_oid;
1091 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
1092 &head_oid, NULL) ||
1093 !(head_commit = lookup_commit_reference_gently(revs.repo,
1094 &head_oid, 1)))
1095 die("no such ref: HEAD");
1097 add_pending_object(&revs, &head_commit->object, "HEAD");
1100 init_scoreboard(&sb);
1101 sb.revs = &revs;
1102 sb.contents_from = contents_from;
1103 sb.reverse = reverse;
1104 sb.repo = the_repository;
1105 sb.path = path;
1106 build_ignorelist(&sb, &ignore_revs_file_list, &ignore_rev_list);
1107 string_list_clear(&ignore_revs_file_list, 0);
1108 string_list_clear(&ignore_rev_list, 0);
1109 setup_scoreboard(&sb, &o);
1112 * Changed-path Bloom filters are disabled when looking
1113 * for copies.
1115 if (!(opt & PICKAXE_BLAME_COPY))
1116 setup_blame_bloom_data(&sb);
1118 lno = sb.num_lines;
1120 if (lno && !range_list.nr)
1121 string_list_append(&range_list, "1");
1123 anchor = 1;
1124 range_set_init(&ranges, range_list.nr);
1125 for (range_i = 0; range_i < range_list.nr; ++range_i) {
1126 long bottom, top;
1127 if (parse_range_arg(range_list.items[range_i].string,
1128 nth_line_cb, &sb, lno, anchor,
1129 &bottom, &top, sb.path,
1130 the_repository->index))
1131 usage(str_usage);
1132 if ((!lno && (top || bottom)) || lno < bottom)
1133 die(Q_("file %s has only %lu line",
1134 "file %s has only %lu lines",
1135 lno), sb.path, lno);
1136 if (bottom < 1)
1137 bottom = 1;
1138 if (top < 1 || lno < top)
1139 top = lno;
1140 bottom--;
1141 range_set_append_unsafe(&ranges, bottom, top);
1142 anchor = top + 1;
1144 sort_and_merge_range_set(&ranges);
1146 for (range_i = ranges.nr; range_i > 0; --range_i) {
1147 const struct range *r = &ranges.ranges[range_i - 1];
1148 ent = blame_entry_prepend(ent, r->start, r->end, o);
1149 num_lines += (r->end - r->start);
1151 if (!num_lines)
1152 num_lines = sb.num_lines;
1154 o->suspects = ent;
1155 prio_queue_put(&sb.commits, o->commit);
1157 blame_origin_decref(o);
1159 range_set_release(&ranges);
1160 string_list_clear(&range_list, 0);
1162 sb.ent = NULL;
1164 if (blame_move_score)
1165 sb.move_score = blame_move_score;
1166 if (blame_copy_score)
1167 sb.copy_score = blame_copy_score;
1169 sb.debug = DEBUG_BLAME;
1170 sb.on_sanity_fail = &sanity_check_on_fail;
1172 sb.show_root = show_root;
1173 sb.xdl_opts = xdl_opts;
1174 sb.no_whole_file_rename = no_whole_file_rename;
1176 read_mailmap(&mailmap);
1178 sb.found_guilty_entry = &found_guilty_entry;
1179 sb.found_guilty_entry_data = &pi;
1180 if (show_progress)
1181 pi.progress = start_delayed_progress(_("Blaming lines"), num_lines);
1183 assign_blame(&sb, opt);
1185 stop_progress(&pi.progress);
1187 if (!incremental)
1188 setup_pager();
1189 else
1190 goto cleanup;
1192 blame_sort_final(&sb);
1194 blame_coalesce(&sb);
1196 if (!(output_option & (OUTPUT_COLOR_LINE | OUTPUT_SHOW_AGE_WITH_COLOR)))
1197 output_option |= coloring_mode;
1199 if (!(output_option & OUTPUT_PORCELAIN)) {
1200 find_alignment(&sb, &output_option);
1201 if (!*repeated_meta_color &&
1202 (output_option & OUTPUT_COLOR_LINE))
1203 xsnprintf(repeated_meta_color,
1204 sizeof(repeated_meta_color),
1205 "%s", GIT_COLOR_CYAN);
1207 if (output_option & OUTPUT_ANNOTATE_COMPAT)
1208 output_option &= ~(OUTPUT_COLOR_LINE | OUTPUT_SHOW_AGE_WITH_COLOR);
1210 output(&sb, output_option);
1211 free((void *)sb.final_buf);
1212 for (ent = sb.ent; ent; ) {
1213 struct blame_entry *e = ent->next;
1214 free(ent);
1215 ent = e;
1218 if (show_stats) {
1219 printf("num read blob: %d\n", sb.num_read_blob);
1220 printf("num get patch: %d\n", sb.num_get_patch);
1221 printf("num commits: %d\n", sb.num_commits);
1224 cleanup:
1225 cleanup_scoreboard(&sb);
1226 release_revisions(&revs);
1227 return 0;