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