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