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