cocci: apply the "cache.h" part of "the_repository.pending"
[alt-git.git] / builtin / blame.c
blob0155062de11ea8bf5c4cde3084146c98e301046a
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 = repo_find_unique_abbrev(the_repository,
605 &suspect->commit->object.oid,
606 auto_abbrev);
607 int len = strlen(uniq);
608 if (auto_abbrev < len)
609 return len;
610 return auto_abbrev;
614 * How many columns do we need to show line numbers, authors,
615 * and filenames?
617 static void find_alignment(struct blame_scoreboard *sb, int *option)
619 int longest_src_lines = 0;
620 int longest_dst_lines = 0;
621 unsigned largest_score = 0;
622 struct blame_entry *e;
623 int compute_auto_abbrev = (abbrev < 0);
624 int auto_abbrev = DEFAULT_ABBREV;
626 for (e = sb->ent; e; e = e->next) {
627 struct blame_origin *suspect = e->suspect;
628 int num;
630 if (compute_auto_abbrev)
631 auto_abbrev = update_auto_abbrev(auto_abbrev, suspect);
632 if (strcmp(suspect->path, sb->path))
633 *option |= OUTPUT_SHOW_NAME;
634 num = strlen(suspect->path);
635 if (longest_file < num)
636 longest_file = num;
637 if (!(suspect->commit->object.flags & METAINFO_SHOWN)) {
638 struct commit_info ci = COMMIT_INFO_INIT;
639 suspect->commit->object.flags |= METAINFO_SHOWN;
640 get_commit_info(suspect->commit, &ci, 1);
641 if (*option & OUTPUT_SHOW_EMAIL)
642 num = utf8_strwidth(ci.author_mail.buf);
643 else
644 num = utf8_strwidth(ci.author.buf);
645 if (longest_author < num)
646 longest_author = num;
647 commit_info_destroy(&ci);
649 num = e->s_lno + e->num_lines;
650 if (longest_src_lines < num)
651 longest_src_lines = num;
652 num = e->lno + e->num_lines;
653 if (longest_dst_lines < num)
654 longest_dst_lines = num;
655 if (largest_score < blame_entry_score(sb, e))
656 largest_score = blame_entry_score(sb, e);
658 max_orig_digits = decimal_width(longest_src_lines);
659 max_digits = decimal_width(longest_dst_lines);
660 max_score_digits = decimal_width(largest_score);
662 if (compute_auto_abbrev)
663 /* one more abbrev length is needed for the boundary commit */
664 abbrev = auto_abbrev + 1;
667 static void sanity_check_on_fail(struct blame_scoreboard *sb, int baa)
669 int opt = OUTPUT_SHOW_SCORE | OUTPUT_SHOW_NUMBER | OUTPUT_SHOW_NAME;
670 find_alignment(sb, &opt);
671 output(sb, opt);
672 die("Baa %d!", baa);
675 static unsigned parse_score(const char *arg)
677 char *end;
678 unsigned long score = strtoul(arg, &end, 10);
679 if (*end)
680 return 0;
681 return score;
684 static const char *add_prefix(const char *prefix, const char *path)
686 return prefix_path(prefix, prefix ? strlen(prefix) : 0, path);
689 static int git_blame_config(const char *var, const char *value, void *cb)
691 if (!strcmp(var, "blame.showroot")) {
692 show_root = git_config_bool(var, value);
693 return 0;
695 if (!strcmp(var, "blame.blankboundary")) {
696 blank_boundary = git_config_bool(var, value);
697 return 0;
699 if (!strcmp(var, "blame.showemail")) {
700 int *output_option = cb;
701 if (git_config_bool(var, value))
702 *output_option |= OUTPUT_SHOW_EMAIL;
703 else
704 *output_option &= ~OUTPUT_SHOW_EMAIL;
705 return 0;
707 if (!strcmp(var, "blame.date")) {
708 if (!value)
709 return config_error_nonbool(var);
710 parse_date_format(value, &blame_date_mode);
711 return 0;
713 if (!strcmp(var, "blame.ignorerevsfile")) {
714 const char *str;
715 int ret;
717 ret = git_config_pathname(&str, var, value);
718 if (ret)
719 return ret;
720 string_list_insert(&ignore_revs_file_list, str);
721 return 0;
723 if (!strcmp(var, "blame.markunblamablelines")) {
724 mark_unblamable_lines = git_config_bool(var, value);
725 return 0;
727 if (!strcmp(var, "blame.markignoredlines")) {
728 mark_ignored_lines = git_config_bool(var, value);
729 return 0;
731 if (!strcmp(var, "color.blame.repeatedlines")) {
732 if (color_parse_mem(value, strlen(value), repeated_meta_color))
733 warning(_("invalid value for '%s': '%s'"),
734 "color.blame.repeatedLines", value);
735 return 0;
737 if (!strcmp(var, "color.blame.highlightrecent")) {
738 parse_color_fields(value);
739 return 0;
742 if (!strcmp(var, "blame.coloring")) {
743 if (!strcmp(value, "repeatedLines")) {
744 coloring_mode |= OUTPUT_COLOR_LINE;
745 } else if (!strcmp(value, "highlightRecent")) {
746 coloring_mode |= OUTPUT_SHOW_AGE_WITH_COLOR;
747 } else if (!strcmp(value, "none")) {
748 coloring_mode &= ~(OUTPUT_COLOR_LINE |
749 OUTPUT_SHOW_AGE_WITH_COLOR);
750 } else {
751 warning(_("invalid value for '%s': '%s'"),
752 "blame.coloring", value);
753 return 0;
757 if (git_diff_heuristic_config(var, value, cb) < 0)
758 return -1;
759 if (userdiff_config(var, value) < 0)
760 return -1;
762 return git_default_config(var, value, cb);
765 static int blame_copy_callback(const struct option *option, const char *arg, int unset)
767 int *opt = option->value;
769 BUG_ON_OPT_NEG(unset);
772 * -C enables copy from removed files;
773 * -C -C enables copy from existing files, but only
774 * when blaming a new file;
775 * -C -C -C enables copy from existing files for
776 * everybody
778 if (*opt & PICKAXE_BLAME_COPY_HARDER)
779 *opt |= PICKAXE_BLAME_COPY_HARDEST;
780 if (*opt & PICKAXE_BLAME_COPY)
781 *opt |= PICKAXE_BLAME_COPY_HARDER;
782 *opt |= PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE;
784 if (arg)
785 blame_copy_score = parse_score(arg);
786 return 0;
789 static int blame_move_callback(const struct option *option, const char *arg, int unset)
791 int *opt = option->value;
793 BUG_ON_OPT_NEG(unset);
795 *opt |= PICKAXE_BLAME_MOVE;
797 if (arg)
798 blame_move_score = parse_score(arg);
799 return 0;
802 static int is_a_rev(const char *name)
804 struct object_id oid;
806 if (repo_get_oid(the_repository, name, &oid))
807 return 0;
808 return OBJ_NONE < oid_object_info(the_repository, &oid, NULL);
811 static int peel_to_commit_oid(struct object_id *oid_ret, void *cbdata)
813 struct repository *r = ((struct blame_scoreboard *)cbdata)->repo;
814 struct object_id oid;
816 oidcpy(&oid, oid_ret);
817 while (1) {
818 struct object *obj;
819 int kind = oid_object_info(r, &oid, NULL);
820 if (kind == OBJ_COMMIT) {
821 oidcpy(oid_ret, &oid);
822 return 0;
824 if (kind != OBJ_TAG)
825 return -1;
826 obj = deref_tag(r, parse_object(r, &oid), NULL, 0);
827 if (!obj)
828 return -1;
829 oidcpy(&oid, &obj->oid);
833 static void build_ignorelist(struct blame_scoreboard *sb,
834 struct string_list *ignore_revs_file_list,
835 struct string_list *ignore_rev_list)
837 struct string_list_item *i;
838 struct object_id oid;
840 oidset_init(&sb->ignore_list, 0);
841 for_each_string_list_item(i, ignore_revs_file_list) {
842 if (!strcmp(i->string, ""))
843 oidset_clear(&sb->ignore_list);
844 else
845 oidset_parse_file_carefully(&sb->ignore_list, i->string,
846 peel_to_commit_oid, sb);
848 for_each_string_list_item(i, ignore_rev_list) {
849 if (repo_get_oid_committish(the_repository, i->string, &oid) ||
850 peel_to_commit_oid(&oid, sb))
851 die(_("cannot find revision %s to ignore"), i->string);
852 oidset_insert(&sb->ignore_list, &oid);
856 int cmd_blame(int argc, const char **argv, const char *prefix)
858 struct rev_info revs;
859 const char *path;
860 struct blame_scoreboard sb;
861 struct blame_origin *o;
862 struct blame_entry *ent = NULL;
863 long dashdash_pos, lno;
864 struct progress_info pi = { NULL, 0 };
866 struct string_list range_list = STRING_LIST_INIT_NODUP;
867 struct string_list ignore_rev_list = STRING_LIST_INIT_NODUP;
868 int output_option = 0, opt = 0;
869 int show_stats = 0;
870 const char *revs_file = NULL;
871 const char *contents_from = NULL;
872 const struct option options[] = {
873 OPT_BOOL(0, "incremental", &incremental, N_("show blame entries as we find them, incrementally")),
874 OPT_BOOL('b', NULL, &blank_boundary, N_("do not show object names of boundary commits (Default: off)")),
875 OPT_BOOL(0, "root", &show_root, N_("do not treat root commits as boundaries (Default: off)")),
876 OPT_BOOL(0, "show-stats", &show_stats, N_("show work cost statistics")),
877 OPT_BOOL(0, "progress", &show_progress, N_("force progress reporting")),
878 OPT_BIT(0, "score-debug", &output_option, N_("show output score for blame entries"), OUTPUT_SHOW_SCORE),
879 OPT_BIT('f', "show-name", &output_option, N_("show original filename (Default: auto)"), OUTPUT_SHOW_NAME),
880 OPT_BIT('n', "show-number", &output_option, N_("show original linenumber (Default: off)"), OUTPUT_SHOW_NUMBER),
881 OPT_BIT('p', "porcelain", &output_option, N_("show in a format designed for machine consumption"), OUTPUT_PORCELAIN),
882 OPT_BIT(0, "line-porcelain", &output_option, N_("show porcelain format with per-line commit information"), OUTPUT_PORCELAIN|OUTPUT_LINE_PORCELAIN),
883 OPT_BIT('c', NULL, &output_option, N_("use the same output mode as git-annotate (Default: off)"), OUTPUT_ANNOTATE_COMPAT),
884 OPT_BIT('t', NULL, &output_option, N_("show raw timestamp (Default: off)"), OUTPUT_RAW_TIMESTAMP),
885 OPT_BIT('l', NULL, &output_option, N_("show long commit SHA1 (Default: off)"), OUTPUT_LONG_OBJECT_NAME),
886 OPT_BIT('s', NULL, &output_option, N_("suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),
887 OPT_BIT('e', "show-email", &output_option, N_("show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),
888 OPT_BIT('w', NULL, &xdl_opts, N_("ignore whitespace differences"), XDF_IGNORE_WHITESPACE),
889 OPT_STRING_LIST(0, "ignore-rev", &ignore_rev_list, N_("rev"), N_("ignore <rev> when blaming")),
890 OPT_STRING_LIST(0, "ignore-revs-file", &ignore_revs_file_list, N_("file"), N_("ignore revisions from <file>")),
891 OPT_BIT(0, "color-lines", &output_option, N_("color redundant metadata from previous line differently"), OUTPUT_COLOR_LINE),
892 OPT_BIT(0, "color-by-age", &output_option, N_("color lines by age"), OUTPUT_SHOW_AGE_WITH_COLOR),
893 OPT_BIT(0, "minimal", &xdl_opts, N_("spend extra cycles to find better match"), XDF_NEED_MINIMAL),
894 OPT_STRING('S', NULL, &revs_file, N_("file"), N_("use revisions from <file> instead of calling git-rev-list")),
895 OPT_STRING(0, "contents", &contents_from, N_("file"), N_("use <file>'s contents as the final image")),
896 OPT_CALLBACK_F('C', NULL, &opt, N_("score"), N_("find line copies within and across files"), PARSE_OPT_OPTARG, blame_copy_callback),
897 OPT_CALLBACK_F('M', NULL, &opt, N_("score"), N_("find line movements within and across files"), PARSE_OPT_OPTARG, blame_move_callback),
898 OPT_STRING_LIST('L', NULL, &range_list, N_("range"),
899 N_("process only line range <start>,<end> or function :<funcname>")),
900 OPT__ABBREV(&abbrev),
901 OPT_END()
904 struct parse_opt_ctx_t ctx;
905 int cmd_is_annotate = !strcmp(argv[0], "annotate");
906 struct range_set ranges;
907 unsigned int range_i;
908 long anchor;
909 const int hexsz = the_hash_algo->hexsz;
910 long num_lines = 0;
911 const char *str_usage = cmd_is_annotate ? annotate_usage : blame_usage;
912 const char **opt_usage = cmd_is_annotate ? annotate_opt_usage : blame_opt_usage;
914 setup_default_color_by_age();
915 git_config(git_blame_config, &output_option);
916 repo_init_revisions(the_repository, &revs, NULL);
917 revs.date_mode = blame_date_mode;
918 revs.diffopt.flags.allow_textconv = 1;
919 revs.diffopt.flags.follow_renames = 1;
921 save_commit_buffer = 0;
922 dashdash_pos = 0;
923 show_progress = -1;
925 parse_options_start(&ctx, argc, argv, prefix, options,
926 PARSE_OPT_KEEP_DASHDASH | PARSE_OPT_KEEP_ARGV0);
927 for (;;) {
928 switch (parse_options_step(&ctx, options, opt_usage)) {
929 case PARSE_OPT_NON_OPTION:
930 case PARSE_OPT_UNKNOWN:
931 break;
932 case PARSE_OPT_HELP:
933 case PARSE_OPT_ERROR:
934 case PARSE_OPT_SUBCOMMAND:
935 exit(129);
936 case PARSE_OPT_COMPLETE:
937 exit(0);
938 case PARSE_OPT_DONE:
939 if (ctx.argv[0])
940 dashdash_pos = ctx.cpidx;
941 goto parse_done;
944 if (!strcmp(ctx.argv[0], "--reverse")) {
945 ctx.argv[0] = "--children";
946 reverse = 1;
948 parse_revision_opt(&revs, &ctx, options, opt_usage);
950 parse_done:
951 revision_opts_finish(&revs);
952 no_whole_file_rename = !revs.diffopt.flags.follow_renames;
953 xdl_opts |= revs.diffopt.xdl_opts & XDF_INDENT_HEURISTIC;
954 revs.diffopt.flags.follow_renames = 0;
955 argc = parse_options_end(&ctx);
957 prepare_repo_settings(the_repository);
958 the_repository->settings.command_requires_full_index = 0;
960 if (incremental || (output_option & OUTPUT_PORCELAIN)) {
961 if (show_progress > 0)
962 die(_("--progress can't be used with --incremental or porcelain formats"));
963 show_progress = 0;
964 } else if (show_progress < 0)
965 show_progress = isatty(2);
967 if (0 < abbrev && abbrev < hexsz)
968 /* one more abbrev length is needed for the boundary commit */
969 abbrev++;
970 else if (!abbrev)
971 abbrev = hexsz;
973 if (revs_file && read_ancestry(revs_file))
974 die_errno("reading graft file '%s' failed", revs_file);
976 if (cmd_is_annotate) {
977 output_option |= OUTPUT_ANNOTATE_COMPAT;
978 blame_date_mode.type = DATE_ISO8601;
979 } else {
980 blame_date_mode = revs.date_mode;
983 /* The maximum width used to show the dates */
984 switch (blame_date_mode.type) {
985 case DATE_RFC2822:
986 blame_date_width = sizeof("Thu, 19 Oct 2006 16:00:04 -0700");
987 break;
988 case DATE_ISO8601_STRICT:
989 blame_date_width = sizeof("2006-10-19T16:00:04-07:00");
990 break;
991 case DATE_ISO8601:
992 blame_date_width = sizeof("2006-10-19 16:00:04 -0700");
993 break;
994 case DATE_RAW:
995 blame_date_width = sizeof("1161298804 -0700");
996 break;
997 case DATE_UNIX:
998 blame_date_width = sizeof("1161298804");
999 break;
1000 case DATE_SHORT:
1001 blame_date_width = sizeof("2006-10-19");
1002 break;
1003 case DATE_RELATIVE:
1005 * TRANSLATORS: This string is used to tell us the
1006 * maximum display width for a relative timestamp in
1007 * "git blame" output. For C locale, "4 years, 11
1008 * months ago", which takes 22 places, is the longest
1009 * among various forms of relative timestamps, but
1010 * your language may need more or fewer display
1011 * columns.
1013 blame_date_width = utf8_strwidth(_("4 years, 11 months ago")) + 1; /* add the null */
1014 break;
1015 case DATE_HUMAN:
1016 /* If the year is shown, no time is shown */
1017 blame_date_width = sizeof("Thu Oct 19 16:00");
1018 break;
1019 case DATE_NORMAL:
1020 blame_date_width = sizeof("Thu Oct 19 16:00:04 2006 -0700");
1021 break;
1022 case DATE_STRFTIME:
1023 blame_date_width = strlen(show_date(0, 0, &blame_date_mode)) + 1; /* add the null */
1024 break;
1026 blame_date_width -= 1; /* strip the null */
1028 if (revs.diffopt.flags.find_copies_harder)
1029 opt |= (PICKAXE_BLAME_COPY | PICKAXE_BLAME_MOVE |
1030 PICKAXE_BLAME_COPY_HARDER);
1033 * We have collected options unknown to us in argv[1..unk]
1034 * which are to be passed to revision machinery if we are
1035 * going to do the "bottom" processing.
1037 * The remaining are:
1039 * (1) if dashdash_pos != 0, it is either
1040 * "blame [revisions] -- <path>" or
1041 * "blame -- <path> <rev>"
1043 * (2) otherwise, it is one of the two:
1044 * "blame [revisions] <path>"
1045 * "blame <path> <rev>"
1047 * Note that we must strip out <path> from the arguments: we do not
1048 * want the path pruning but we may want "bottom" processing.
1050 if (dashdash_pos) {
1051 switch (argc - dashdash_pos - 1) {
1052 case 2: /* (1b) */
1053 if (argc != 4)
1054 usage_with_options(opt_usage, options);
1055 /* reorder for the new way: <rev> -- <path> */
1056 argv[1] = argv[3];
1057 argv[3] = argv[2];
1058 argv[2] = "--";
1059 /* FALLTHROUGH */
1060 case 1: /* (1a) */
1061 path = add_prefix(prefix, argv[--argc]);
1062 argv[argc] = NULL;
1063 break;
1064 default:
1065 usage_with_options(opt_usage, options);
1067 } else {
1068 if (argc < 2)
1069 usage_with_options(opt_usage, options);
1070 if (argc == 3 && is_a_rev(argv[argc - 1])) { /* (2b) */
1071 path = add_prefix(prefix, argv[1]);
1072 argv[1] = argv[2];
1073 } else { /* (2a) */
1074 if (argc == 2 && is_a_rev(argv[1]) && !get_git_work_tree())
1075 die("missing <path> to blame");
1076 path = add_prefix(prefix, argv[argc - 1]);
1078 argv[argc - 1] = "--";
1081 revs.disable_stdin = 1;
1082 setup_revisions(argc, argv, &revs, NULL);
1083 if (!revs.pending.nr && is_bare_repository()) {
1084 struct commit *head_commit;
1085 struct object_id head_oid;
1087 if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
1088 &head_oid, NULL) ||
1089 !(head_commit = lookup_commit_reference_gently(revs.repo,
1090 &head_oid, 1)))
1091 die("no such ref: HEAD");
1093 add_pending_object(&revs, &head_commit->object, "HEAD");
1096 init_scoreboard(&sb);
1097 sb.revs = &revs;
1098 sb.contents_from = contents_from;
1099 sb.reverse = reverse;
1100 sb.repo = the_repository;
1101 sb.path = path;
1102 build_ignorelist(&sb, &ignore_revs_file_list, &ignore_rev_list);
1103 string_list_clear(&ignore_revs_file_list, 0);
1104 string_list_clear(&ignore_rev_list, 0);
1105 setup_scoreboard(&sb, &o);
1108 * Changed-path Bloom filters are disabled when looking
1109 * for copies.
1111 if (!(opt & PICKAXE_BLAME_COPY))
1112 setup_blame_bloom_data(&sb);
1114 lno = sb.num_lines;
1116 if (lno && !range_list.nr)
1117 string_list_append(&range_list, "1");
1119 anchor = 1;
1120 range_set_init(&ranges, range_list.nr);
1121 for (range_i = 0; range_i < range_list.nr; ++range_i) {
1122 long bottom, top;
1123 if (parse_range_arg(range_list.items[range_i].string,
1124 nth_line_cb, &sb, lno, anchor,
1125 &bottom, &top, sb.path,
1126 the_repository->index))
1127 usage(str_usage);
1128 if ((!lno && (top || bottom)) || lno < bottom)
1129 die(Q_("file %s has only %lu line",
1130 "file %s has only %lu lines",
1131 lno), sb.path, lno);
1132 if (bottom < 1)
1133 bottom = 1;
1134 if (top < 1 || lno < top)
1135 top = lno;
1136 bottom--;
1137 range_set_append_unsafe(&ranges, bottom, top);
1138 anchor = top + 1;
1140 sort_and_merge_range_set(&ranges);
1142 for (range_i = ranges.nr; range_i > 0; --range_i) {
1143 const struct range *r = &ranges.ranges[range_i - 1];
1144 ent = blame_entry_prepend(ent, r->start, r->end, o);
1145 num_lines += (r->end - r->start);
1147 if (!num_lines)
1148 num_lines = sb.num_lines;
1150 o->suspects = ent;
1151 prio_queue_put(&sb.commits, o->commit);
1153 blame_origin_decref(o);
1155 range_set_release(&ranges);
1156 string_list_clear(&range_list, 0);
1158 sb.ent = NULL;
1160 if (blame_move_score)
1161 sb.move_score = blame_move_score;
1162 if (blame_copy_score)
1163 sb.copy_score = blame_copy_score;
1165 sb.debug = DEBUG_BLAME;
1166 sb.on_sanity_fail = &sanity_check_on_fail;
1168 sb.show_root = show_root;
1169 sb.xdl_opts = xdl_opts;
1170 sb.no_whole_file_rename = no_whole_file_rename;
1172 read_mailmap(&mailmap);
1174 sb.found_guilty_entry = &found_guilty_entry;
1175 sb.found_guilty_entry_data = &pi;
1176 if (show_progress)
1177 pi.progress = start_delayed_progress(_("Blaming lines"), num_lines);
1179 assign_blame(&sb, opt);
1181 stop_progress(&pi.progress);
1183 if (!incremental)
1184 setup_pager();
1185 else
1186 goto cleanup;
1188 blame_sort_final(&sb);
1190 blame_coalesce(&sb);
1192 if (!(output_option & (OUTPUT_COLOR_LINE | OUTPUT_SHOW_AGE_WITH_COLOR)))
1193 output_option |= coloring_mode;
1195 if (!(output_option & OUTPUT_PORCELAIN)) {
1196 find_alignment(&sb, &output_option);
1197 if (!*repeated_meta_color &&
1198 (output_option & OUTPUT_COLOR_LINE))
1199 xsnprintf(repeated_meta_color,
1200 sizeof(repeated_meta_color),
1201 "%s", GIT_COLOR_CYAN);
1203 if (output_option & OUTPUT_ANNOTATE_COMPAT)
1204 output_option &= ~(OUTPUT_COLOR_LINE | OUTPUT_SHOW_AGE_WITH_COLOR);
1206 output(&sb, output_option);
1207 free((void *)sb.final_buf);
1208 for (ent = sb.ent; ent; ) {
1209 struct blame_entry *e = ent->next;
1210 free(ent);
1211 ent = e;
1214 if (show_stats) {
1215 printf("num read blob: %d\n", sb.num_read_blob);
1216 printf("num get patch: %d\n", sb.num_get_patch);
1217 printf("num commits: %d\n", sb.num_commits);
1220 cleanup:
1221 cleanup_scoreboard(&sb);
1222 release_revisions(&revs);
1223 return 0;