diff.con commit blame: honor the diff heuristic options and config (5b16287)
   1/*
   2 * Copyright (C) 2005 Junio C Hamano
   3 */
   4#include "cache.h"
   5#include "tempfile.h"
   6#include "quote.h"
   7#include "diff.h"
   8#include "diffcore.h"
   9#include "delta.h"
  10#include "xdiff-interface.h"
  11#include "color.h"
  12#include "attr.h"
  13#include "run-command.h"
  14#include "utf8.h"
  15#include "userdiff.h"
  16#include "submodule-config.h"
  17#include "submodule.h"
  18#include "ll-merge.h"
  19#include "string-list.h"
  20#include "argv-array.h"
  21
  22#ifdef NO_FAST_WORKING_DIRECTORY
  23#define FAST_WORKING_DIRECTORY 0
  24#else
  25#define FAST_WORKING_DIRECTORY 1
  26#endif
  27
  28static int diff_detect_rename_default;
  29static int diff_indent_heuristic; /* experimental */
  30static int diff_compaction_heuristic; /* experimental */
  31static int diff_rename_limit_default = 400;
  32static int diff_suppress_blank_empty;
  33static int diff_use_color_default = -1;
  34static int diff_context_default = 3;
  35static const char *diff_word_regex_cfg;
  36static const char *external_diff_cmd_cfg;
  37static const char *diff_order_file_cfg;
  38int diff_auto_refresh_index = 1;
  39static int diff_mnemonic_prefix;
  40static int diff_no_prefix;
  41static int diff_stat_graph_width;
  42static int diff_dirstat_permille_default = 30;
  43static struct diff_options default_diff_options;
  44static long diff_algorithm;
  45
  46static char diff_colors[][COLOR_MAXLEN] = {
  47        GIT_COLOR_RESET,
  48        GIT_COLOR_NORMAL,       /* CONTEXT */
  49        GIT_COLOR_BOLD,         /* METAINFO */
  50        GIT_COLOR_CYAN,         /* FRAGINFO */
  51        GIT_COLOR_RED,          /* OLD */
  52        GIT_COLOR_GREEN,        /* NEW */
  53        GIT_COLOR_YELLOW,       /* COMMIT */
  54        GIT_COLOR_BG_RED,       /* WHITESPACE */
  55        GIT_COLOR_NORMAL,       /* FUNCINFO */
  56};
  57
  58static int parse_diff_color_slot(const char *var)
  59{
  60        if (!strcasecmp(var, "context") || !strcasecmp(var, "plain"))
  61                return DIFF_CONTEXT;
  62        if (!strcasecmp(var, "meta"))
  63                return DIFF_METAINFO;
  64        if (!strcasecmp(var, "frag"))
  65                return DIFF_FRAGINFO;
  66        if (!strcasecmp(var, "old"))
  67                return DIFF_FILE_OLD;
  68        if (!strcasecmp(var, "new"))
  69                return DIFF_FILE_NEW;
  70        if (!strcasecmp(var, "commit"))
  71                return DIFF_COMMIT;
  72        if (!strcasecmp(var, "whitespace"))
  73                return DIFF_WHITESPACE;
  74        if (!strcasecmp(var, "func"))
  75                return DIFF_FUNCINFO;
  76        return -1;
  77}
  78
  79static int parse_dirstat_params(struct diff_options *options, const char *params_string,
  80                                struct strbuf *errmsg)
  81{
  82        char *params_copy = xstrdup(params_string);
  83        struct string_list params = STRING_LIST_INIT_NODUP;
  84        int ret = 0;
  85        int i;
  86
  87        if (*params_copy)
  88                string_list_split_in_place(&params, params_copy, ',', -1);
  89        for (i = 0; i < params.nr; i++) {
  90                const char *p = params.items[i].string;
  91                if (!strcmp(p, "changes")) {
  92                        DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
  93                        DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
  94                } else if (!strcmp(p, "lines")) {
  95                        DIFF_OPT_SET(options, DIRSTAT_BY_LINE);
  96                        DIFF_OPT_CLR(options, DIRSTAT_BY_FILE);
  97                } else if (!strcmp(p, "files")) {
  98                        DIFF_OPT_CLR(options, DIRSTAT_BY_LINE);
  99                        DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
 100                } else if (!strcmp(p, "noncumulative")) {
 101                        DIFF_OPT_CLR(options, DIRSTAT_CUMULATIVE);
 102                } else if (!strcmp(p, "cumulative")) {
 103                        DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
 104                } else if (isdigit(*p)) {
 105                        char *end;
 106                        int permille = strtoul(p, &end, 10) * 10;
 107                        if (*end == '.' && isdigit(*++end)) {
 108                                /* only use first digit */
 109                                permille += *end - '0';
 110                                /* .. and ignore any further digits */
 111                                while (isdigit(*++end))
 112                                        ; /* nothing */
 113                        }
 114                        if (!*end)
 115                                options->dirstat_permille = permille;
 116                        else {
 117                                strbuf_addf(errmsg, _("  Failed to parse dirstat cut-off percentage '%s'\n"),
 118                                            p);
 119                                ret++;
 120                        }
 121                } else {
 122                        strbuf_addf(errmsg, _("  Unknown dirstat parameter '%s'\n"), p);
 123                        ret++;
 124                }
 125
 126        }
 127        string_list_clear(&params, 0);
 128        free(params_copy);
 129        return ret;
 130}
 131
 132static int parse_submodule_params(struct diff_options *options, const char *value)
 133{
 134        if (!strcmp(value, "log"))
 135                DIFF_OPT_SET(options, SUBMODULE_LOG);
 136        else if (!strcmp(value, "short"))
 137                DIFF_OPT_CLR(options, SUBMODULE_LOG);
 138        else
 139                return -1;
 140        return 0;
 141}
 142
 143static int git_config_rename(const char *var, const char *value)
 144{
 145        if (!value)
 146                return DIFF_DETECT_RENAME;
 147        if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
 148                return  DIFF_DETECT_COPY;
 149        return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
 150}
 151
 152long parse_algorithm_value(const char *value)
 153{
 154        if (!value)
 155                return -1;
 156        else if (!strcasecmp(value, "myers") || !strcasecmp(value, "default"))
 157                return 0;
 158        else if (!strcasecmp(value, "minimal"))
 159                return XDF_NEED_MINIMAL;
 160        else if (!strcasecmp(value, "patience"))
 161                return XDF_PATIENCE_DIFF;
 162        else if (!strcasecmp(value, "histogram"))
 163                return XDF_HISTOGRAM_DIFF;
 164        return -1;
 165}
 166
 167/*
 168 * These are to give UI layer defaults.
 169 * The core-level commands such as git-diff-files should
 170 * never be affected by the setting of diff.renames
 171 * the user happens to have in the configuration file.
 172 */
 173void init_diff_ui_defaults(void)
 174{
 175        diff_detect_rename_default = 1;
 176}
 177
 178int git_diff_heuristic_config(const char *var, const char *value, void *cb)
 179{
 180        if (!strcmp(var, "diff.indentheuristic")) {
 181                diff_indent_heuristic = git_config_bool(var, value);
 182                if (diff_indent_heuristic)
 183                        diff_compaction_heuristic = 0;
 184        }
 185        if (!strcmp(var, "diff.compactionheuristic")) {
 186                diff_compaction_heuristic = git_config_bool(var, value);
 187                if (diff_compaction_heuristic)
 188                        diff_indent_heuristic = 0;
 189        }
 190        return 0;
 191}
 192
 193int git_diff_ui_config(const char *var, const char *value, void *cb)
 194{
 195        if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
 196                diff_use_color_default = git_config_colorbool(var, value);
 197                return 0;
 198        }
 199        if (!strcmp(var, "diff.context")) {
 200                diff_context_default = git_config_int(var, value);
 201                if (diff_context_default < 0)
 202                        return -1;
 203                return 0;
 204        }
 205        if (!strcmp(var, "diff.renames")) {
 206                diff_detect_rename_default = git_config_rename(var, value);
 207                return 0;
 208        }
 209        if (!strcmp(var, "diff.autorefreshindex")) {
 210                diff_auto_refresh_index = git_config_bool(var, value);
 211                return 0;
 212        }
 213        if (!strcmp(var, "diff.mnemonicprefix")) {
 214                diff_mnemonic_prefix = git_config_bool(var, value);
 215                return 0;
 216        }
 217        if (!strcmp(var, "diff.noprefix")) {
 218                diff_no_prefix = git_config_bool(var, value);
 219                return 0;
 220        }
 221        if (!strcmp(var, "diff.statgraphwidth")) {
 222                diff_stat_graph_width = git_config_int(var, value);
 223                return 0;
 224        }
 225        if (!strcmp(var, "diff.external"))
 226                return git_config_string(&external_diff_cmd_cfg, var, value);
 227        if (!strcmp(var, "diff.wordregex"))
 228                return git_config_string(&diff_word_regex_cfg, var, value);
 229        if (!strcmp(var, "diff.orderfile"))
 230                return git_config_pathname(&diff_order_file_cfg, var, value);
 231
 232        if (!strcmp(var, "diff.ignoresubmodules"))
 233                handle_ignore_submodules_arg(&default_diff_options, value);
 234
 235        if (!strcmp(var, "diff.submodule")) {
 236                if (parse_submodule_params(&default_diff_options, value))
 237                        warning(_("Unknown value for 'diff.submodule' config variable: '%s'"),
 238                                value);
 239                return 0;
 240        }
 241
 242        if (!strcmp(var, "diff.algorithm")) {
 243                diff_algorithm = parse_algorithm_value(value);
 244                if (diff_algorithm < 0)
 245                        return -1;
 246                return 0;
 247        }
 248
 249        if (git_diff_heuristic_config(var, value, cb) < 0)
 250                return -1;
 251        if (git_color_config(var, value, cb) < 0)
 252                return -1;
 253
 254        return git_diff_basic_config(var, value, cb);
 255}
 256
 257int git_diff_basic_config(const char *var, const char *value, void *cb)
 258{
 259        const char *name;
 260
 261        if (!strcmp(var, "diff.renamelimit")) {
 262                diff_rename_limit_default = git_config_int(var, value);
 263                return 0;
 264        }
 265
 266        if (userdiff_config(var, value) < 0)
 267                return -1;
 268
 269        if (skip_prefix(var, "diff.color.", &name) ||
 270            skip_prefix(var, "color.diff.", &name)) {
 271                int slot = parse_diff_color_slot(name);
 272                if (slot < 0)
 273                        return 0;
 274                if (!value)
 275                        return config_error_nonbool(var);
 276                return color_parse(value, diff_colors[slot]);
 277        }
 278
 279        /* like GNU diff's --suppress-blank-empty option  */
 280        if (!strcmp(var, "diff.suppressblankempty") ||
 281                        /* for backwards compatibility */
 282                        !strcmp(var, "diff.suppress-blank-empty")) {
 283                diff_suppress_blank_empty = git_config_bool(var, value);
 284                return 0;
 285        }
 286
 287        if (!strcmp(var, "diff.dirstat")) {
 288                struct strbuf errmsg = STRBUF_INIT;
 289                default_diff_options.dirstat_permille = diff_dirstat_permille_default;
 290                if (parse_dirstat_params(&default_diff_options, value, &errmsg))
 291                        warning(_("Found errors in 'diff.dirstat' config variable:\n%s"),
 292                                errmsg.buf);
 293                strbuf_release(&errmsg);
 294                diff_dirstat_permille_default = default_diff_options.dirstat_permille;
 295                return 0;
 296        }
 297
 298        if (starts_with(var, "submodule."))
 299                return parse_submodule_config_option(var, value);
 300
 301        return git_default_config(var, value, cb);
 302}
 303
 304static char *quote_two(const char *one, const char *two)
 305{
 306        int need_one = quote_c_style(one, NULL, NULL, 1);
 307        int need_two = quote_c_style(two, NULL, NULL, 1);
 308        struct strbuf res = STRBUF_INIT;
 309
 310        if (need_one + need_two) {
 311                strbuf_addch(&res, '"');
 312                quote_c_style(one, &res, NULL, 1);
 313                quote_c_style(two, &res, NULL, 1);
 314                strbuf_addch(&res, '"');
 315        } else {
 316                strbuf_addstr(&res, one);
 317                strbuf_addstr(&res, two);
 318        }
 319        return strbuf_detach(&res, NULL);
 320}
 321
 322static const char *external_diff(void)
 323{
 324        static const char *external_diff_cmd = NULL;
 325        static int done_preparing = 0;
 326
 327        if (done_preparing)
 328                return external_diff_cmd;
 329        external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
 330        if (!external_diff_cmd)
 331                external_diff_cmd = external_diff_cmd_cfg;
 332        done_preparing = 1;
 333        return external_diff_cmd;
 334}
 335
 336/*
 337 * Keep track of files used for diffing. Sometimes such an entry
 338 * refers to a temporary file, sometimes to an existing file, and
 339 * sometimes to "/dev/null".
 340 */
 341static struct diff_tempfile {
 342        /*
 343         * filename external diff should read from, or NULL if this
 344         * entry is currently not in use:
 345         */
 346        const char *name;
 347
 348        char hex[GIT_SHA1_HEXSZ + 1];
 349        char mode[10];
 350
 351        /*
 352         * If this diff_tempfile instance refers to a temporary file,
 353         * this tempfile object is used to manage its lifetime.
 354         */
 355        struct tempfile tempfile;
 356} diff_temp[2];
 357
 358typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
 359
 360struct emit_callback {
 361        int color_diff;
 362        unsigned ws_rule;
 363        int blank_at_eof_in_preimage;
 364        int blank_at_eof_in_postimage;
 365        int lno_in_preimage;
 366        int lno_in_postimage;
 367        sane_truncate_fn truncate;
 368        const char **label_path;
 369        struct diff_words_data *diff_words;
 370        struct diff_options *opt;
 371        int *found_changesp;
 372        struct strbuf *header;
 373};
 374
 375static int count_lines(const char *data, int size)
 376{
 377        int count, ch, completely_empty = 1, nl_just_seen = 0;
 378        count = 0;
 379        while (0 < size--) {
 380                ch = *data++;
 381                if (ch == '\n') {
 382                        count++;
 383                        nl_just_seen = 1;
 384                        completely_empty = 0;
 385                }
 386                else {
 387                        nl_just_seen = 0;
 388                        completely_empty = 0;
 389                }
 390        }
 391        if (completely_empty)
 392                return 0;
 393        if (!nl_just_seen)
 394                count++; /* no trailing newline */
 395        return count;
 396}
 397
 398static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
 399{
 400        if (!DIFF_FILE_VALID(one)) {
 401                mf->ptr = (char *)""; /* does not matter */
 402                mf->size = 0;
 403                return 0;
 404        }
 405        else if (diff_populate_filespec(one, 0))
 406                return -1;
 407
 408        mf->ptr = one->data;
 409        mf->size = one->size;
 410        return 0;
 411}
 412
 413/* like fill_mmfile, but only for size, so we can avoid retrieving blob */
 414static unsigned long diff_filespec_size(struct diff_filespec *one)
 415{
 416        if (!DIFF_FILE_VALID(one))
 417                return 0;
 418        diff_populate_filespec(one, CHECK_SIZE_ONLY);
 419        return one->size;
 420}
 421
 422static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
 423{
 424        char *ptr = mf->ptr;
 425        long size = mf->size;
 426        int cnt = 0;
 427
 428        if (!size)
 429                return cnt;
 430        ptr += size - 1; /* pointing at the very end */
 431        if (*ptr != '\n')
 432                ; /* incomplete line */
 433        else
 434                ptr--; /* skip the last LF */
 435        while (mf->ptr < ptr) {
 436                char *prev_eol;
 437                for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
 438                        if (*prev_eol == '\n')
 439                                break;
 440                if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
 441                        break;
 442                cnt++;
 443                ptr = prev_eol - 1;
 444        }
 445        return cnt;
 446}
 447
 448static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
 449                               struct emit_callback *ecbdata)
 450{
 451        int l1, l2, at;
 452        unsigned ws_rule = ecbdata->ws_rule;
 453        l1 = count_trailing_blank(mf1, ws_rule);
 454        l2 = count_trailing_blank(mf2, ws_rule);
 455        if (l2 <= l1) {
 456                ecbdata->blank_at_eof_in_preimage = 0;
 457                ecbdata->blank_at_eof_in_postimage = 0;
 458                return;
 459        }
 460        at = count_lines(mf1->ptr, mf1->size);
 461        ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
 462
 463        at = count_lines(mf2->ptr, mf2->size);
 464        ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
 465}
 466
 467static void emit_line_0(struct diff_options *o, const char *set, const char *reset,
 468                        int first, const char *line, int len)
 469{
 470        int has_trailing_newline, has_trailing_carriage_return;
 471        int nofirst;
 472        FILE *file = o->file;
 473
 474        fputs(diff_line_prefix(o), file);
 475
 476        if (len == 0) {
 477                has_trailing_newline = (first == '\n');
 478                has_trailing_carriage_return = (!has_trailing_newline &&
 479                                                (first == '\r'));
 480                nofirst = has_trailing_newline || has_trailing_carriage_return;
 481        } else {
 482                has_trailing_newline = (len > 0 && line[len-1] == '\n');
 483                if (has_trailing_newline)
 484                        len--;
 485                has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
 486                if (has_trailing_carriage_return)
 487                        len--;
 488                nofirst = 0;
 489        }
 490
 491        if (len || !nofirst) {
 492                fputs(set, file);
 493                if (!nofirst)
 494                        fputc(first, file);
 495                fwrite(line, len, 1, file);
 496                fputs(reset, file);
 497        }
 498        if (has_trailing_carriage_return)
 499                fputc('\r', file);
 500        if (has_trailing_newline)
 501                fputc('\n', file);
 502}
 503
 504static void emit_line(struct diff_options *o, const char *set, const char *reset,
 505                      const char *line, int len)
 506{
 507        emit_line_0(o, set, reset, line[0], line+1, len-1);
 508}
 509
 510static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
 511{
 512        if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
 513              ecbdata->blank_at_eof_in_preimage &&
 514              ecbdata->blank_at_eof_in_postimage &&
 515              ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
 516              ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
 517                return 0;
 518        return ws_blank_line(line, len, ecbdata->ws_rule);
 519}
 520
 521static void emit_line_checked(const char *reset,
 522                              struct emit_callback *ecbdata,
 523                              const char *line, int len,
 524                              enum color_diff color,
 525                              unsigned ws_error_highlight,
 526                              char sign)
 527{
 528        const char *set = diff_get_color(ecbdata->color_diff, color);
 529        const char *ws = NULL;
 530
 531        if (ecbdata->opt->ws_error_highlight & ws_error_highlight) {
 532                ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
 533                if (!*ws)
 534                        ws = NULL;
 535        }
 536
 537        if (!ws)
 538                emit_line_0(ecbdata->opt, set, reset, sign, line, len);
 539        else if (sign == '+' && new_blank_line_at_eof(ecbdata, line, len))
 540                /* Blank line at EOF - paint '+' as well */
 541                emit_line_0(ecbdata->opt, ws, reset, sign, line, len);
 542        else {
 543                /* Emit just the prefix, then the rest. */
 544                emit_line_0(ecbdata->opt, set, reset, sign, "", 0);
 545                ws_check_emit(line, len, ecbdata->ws_rule,
 546                              ecbdata->opt->file, set, reset, ws);
 547        }
 548}
 549
 550static void emit_add_line(const char *reset,
 551                          struct emit_callback *ecbdata,
 552                          const char *line, int len)
 553{
 554        emit_line_checked(reset, ecbdata, line, len,
 555                          DIFF_FILE_NEW, WSEH_NEW, '+');
 556}
 557
 558static void emit_del_line(const char *reset,
 559                          struct emit_callback *ecbdata,
 560                          const char *line, int len)
 561{
 562        emit_line_checked(reset, ecbdata, line, len,
 563                          DIFF_FILE_OLD, WSEH_OLD, '-');
 564}
 565
 566static void emit_context_line(const char *reset,
 567                              struct emit_callback *ecbdata,
 568                              const char *line, int len)
 569{
 570        emit_line_checked(reset, ecbdata, line, len,
 571                          DIFF_CONTEXT, WSEH_CONTEXT, ' ');
 572}
 573
 574static void emit_hunk_header(struct emit_callback *ecbdata,
 575                             const char *line, int len)
 576{
 577        const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
 578        const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
 579        const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
 580        const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
 581        static const char atat[2] = { '@', '@' };
 582        const char *cp, *ep;
 583        struct strbuf msgbuf = STRBUF_INIT;
 584        int org_len = len;
 585        int i = 1;
 586
 587        /*
 588         * As a hunk header must begin with "@@ -<old>, +<new> @@",
 589         * it always is at least 10 bytes long.
 590         */
 591        if (len < 10 ||
 592            memcmp(line, atat, 2) ||
 593            !(ep = memmem(line + 2, len - 2, atat, 2))) {
 594                emit_line(ecbdata->opt, context, reset, line, len);
 595                return;
 596        }
 597        ep += 2; /* skip over @@ */
 598
 599        /* The hunk header in fraginfo color */
 600        strbuf_addstr(&msgbuf, frag);
 601        strbuf_add(&msgbuf, line, ep - line);
 602        strbuf_addstr(&msgbuf, reset);
 603
 604        /*
 605         * trailing "\r\n"
 606         */
 607        for ( ; i < 3; i++)
 608                if (line[len - i] == '\r' || line[len - i] == '\n')
 609                        len--;
 610
 611        /* blank before the func header */
 612        for (cp = ep; ep - line < len; ep++)
 613                if (*ep != ' ' && *ep != '\t')
 614                        break;
 615        if (ep != cp) {
 616                strbuf_addstr(&msgbuf, context);
 617                strbuf_add(&msgbuf, cp, ep - cp);
 618                strbuf_addstr(&msgbuf, reset);
 619        }
 620
 621        if (ep < line + len) {
 622                strbuf_addstr(&msgbuf, func);
 623                strbuf_add(&msgbuf, ep, line + len - ep);
 624                strbuf_addstr(&msgbuf, reset);
 625        }
 626
 627        strbuf_add(&msgbuf, line + len, org_len - len);
 628        emit_line(ecbdata->opt, "", "", msgbuf.buf, msgbuf.len);
 629        strbuf_release(&msgbuf);
 630}
 631
 632static struct diff_tempfile *claim_diff_tempfile(void) {
 633        int i;
 634        for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
 635                if (!diff_temp[i].name)
 636                        return diff_temp + i;
 637        die("BUG: diff is failing to clean up its tempfiles");
 638}
 639
 640static void remove_tempfile(void)
 641{
 642        int i;
 643        for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
 644                if (is_tempfile_active(&diff_temp[i].tempfile))
 645                        delete_tempfile(&diff_temp[i].tempfile);
 646                diff_temp[i].name = NULL;
 647        }
 648}
 649
 650static void print_line_count(FILE *file, int count)
 651{
 652        switch (count) {
 653        case 0:
 654                fprintf(file, "0,0");
 655                break;
 656        case 1:
 657                fprintf(file, "1");
 658                break;
 659        default:
 660                fprintf(file, "1,%d", count);
 661                break;
 662        }
 663}
 664
 665static void emit_rewrite_lines(struct emit_callback *ecb,
 666                               int prefix, const char *data, int size)
 667{
 668        const char *endp = NULL;
 669        static const char *nneof = " No newline at end of file\n";
 670        const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
 671
 672        while (0 < size) {
 673                int len;
 674
 675                endp = memchr(data, '\n', size);
 676                len = endp ? (endp - data + 1) : size;
 677                if (prefix != '+') {
 678                        ecb->lno_in_preimage++;
 679                        emit_del_line(reset, ecb, data, len);
 680                } else {
 681                        ecb->lno_in_postimage++;
 682                        emit_add_line(reset, ecb, data, len);
 683                }
 684                size -= len;
 685                data += len;
 686        }
 687        if (!endp) {
 688                const char *context = diff_get_color(ecb->color_diff,
 689                                                     DIFF_CONTEXT);
 690                putc('\n', ecb->opt->file);
 691                emit_line_0(ecb->opt, context, reset, '\\',
 692                            nneof, strlen(nneof));
 693        }
 694}
 695
 696static void emit_rewrite_diff(const char *name_a,
 697                              const char *name_b,
 698                              struct diff_filespec *one,
 699                              struct diff_filespec *two,
 700                              struct userdiff_driver *textconv_one,
 701                              struct userdiff_driver *textconv_two,
 702                              struct diff_options *o)
 703{
 704        int lc_a, lc_b;
 705        const char *name_a_tab, *name_b_tab;
 706        const char *metainfo = diff_get_color(o->use_color, DIFF_METAINFO);
 707        const char *fraginfo = diff_get_color(o->use_color, DIFF_FRAGINFO);
 708        const char *reset = diff_get_color(o->use_color, DIFF_RESET);
 709        static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
 710        const char *a_prefix, *b_prefix;
 711        char *data_one, *data_two;
 712        size_t size_one, size_two;
 713        struct emit_callback ecbdata;
 714        const char *line_prefix = diff_line_prefix(o);
 715
 716        if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
 717                a_prefix = o->b_prefix;
 718                b_prefix = o->a_prefix;
 719        } else {
 720                a_prefix = o->a_prefix;
 721                b_prefix = o->b_prefix;
 722        }
 723
 724        name_a += (*name_a == '/');
 725        name_b += (*name_b == '/');
 726        name_a_tab = strchr(name_a, ' ') ? "\t" : "";
 727        name_b_tab = strchr(name_b, ' ') ? "\t" : "";
 728
 729        strbuf_reset(&a_name);
 730        strbuf_reset(&b_name);
 731        quote_two_c_style(&a_name, a_prefix, name_a, 0);
 732        quote_two_c_style(&b_name, b_prefix, name_b, 0);
 733
 734        size_one = fill_textconv(textconv_one, one, &data_one);
 735        size_two = fill_textconv(textconv_two, two, &data_two);
 736
 737        memset(&ecbdata, 0, sizeof(ecbdata));
 738        ecbdata.color_diff = want_color(o->use_color);
 739        ecbdata.found_changesp = &o->found_changes;
 740        ecbdata.ws_rule = whitespace_rule(name_b);
 741        ecbdata.opt = o;
 742        if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
 743                mmfile_t mf1, mf2;
 744                mf1.ptr = (char *)data_one;
 745                mf2.ptr = (char *)data_two;
 746                mf1.size = size_one;
 747                mf2.size = size_two;
 748                check_blank_at_eof(&mf1, &mf2, &ecbdata);
 749        }
 750        ecbdata.lno_in_preimage = 1;
 751        ecbdata.lno_in_postimage = 1;
 752
 753        lc_a = count_lines(data_one, size_one);
 754        lc_b = count_lines(data_two, size_two);
 755        fprintf(o->file,
 756                "%s%s--- %s%s%s\n%s%s+++ %s%s%s\n%s%s@@ -",
 757                line_prefix, metainfo, a_name.buf, name_a_tab, reset,
 758                line_prefix, metainfo, b_name.buf, name_b_tab, reset,
 759                line_prefix, fraginfo);
 760        if (!o->irreversible_delete)
 761                print_line_count(o->file, lc_a);
 762        else
 763                fprintf(o->file, "?,?");
 764        fprintf(o->file, " +");
 765        print_line_count(o->file, lc_b);
 766        fprintf(o->file, " @@%s\n", reset);
 767        if (lc_a && !o->irreversible_delete)
 768                emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
 769        if (lc_b)
 770                emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
 771        if (textconv_one)
 772                free((char *)data_one);
 773        if (textconv_two)
 774                free((char *)data_two);
 775}
 776
 777struct diff_words_buffer {
 778        mmfile_t text;
 779        long alloc;
 780        struct diff_words_orig {
 781                const char *begin, *end;
 782        } *orig;
 783        int orig_nr, orig_alloc;
 784};
 785
 786static void diff_words_append(char *line, unsigned long len,
 787                struct diff_words_buffer *buffer)
 788{
 789        ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
 790        line++;
 791        len--;
 792        memcpy(buffer->text.ptr + buffer->text.size, line, len);
 793        buffer->text.size += len;
 794        buffer->text.ptr[buffer->text.size] = '\0';
 795}
 796
 797struct diff_words_style_elem {
 798        const char *prefix;
 799        const char *suffix;
 800        const char *color; /* NULL; filled in by the setup code if
 801                            * color is enabled */
 802};
 803
 804struct diff_words_style {
 805        enum diff_words_type type;
 806        struct diff_words_style_elem new, old, ctx;
 807        const char *newline;
 808};
 809
 810static struct diff_words_style diff_words_styles[] = {
 811        { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
 812        { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
 813        { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
 814};
 815
 816struct diff_words_data {
 817        struct diff_words_buffer minus, plus;
 818        const char *current_plus;
 819        int last_minus;
 820        struct diff_options *opt;
 821        regex_t *word_regex;
 822        enum diff_words_type type;
 823        struct diff_words_style *style;
 824};
 825
 826static int fn_out_diff_words_write_helper(FILE *fp,
 827                                          struct diff_words_style_elem *st_el,
 828                                          const char *newline,
 829                                          size_t count, const char *buf,
 830                                          const char *line_prefix)
 831{
 832        int print = 0;
 833
 834        while (count) {
 835                char *p = memchr(buf, '\n', count);
 836                if (print)
 837                        fputs(line_prefix, fp);
 838                if (p != buf) {
 839                        if (st_el->color && fputs(st_el->color, fp) < 0)
 840                                return -1;
 841                        if (fputs(st_el->prefix, fp) < 0 ||
 842                            fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
 843                            fputs(st_el->suffix, fp) < 0)
 844                                return -1;
 845                        if (st_el->color && *st_el->color
 846                            && fputs(GIT_COLOR_RESET, fp) < 0)
 847                                return -1;
 848                }
 849                if (!p)
 850                        return 0;
 851                if (fputs(newline, fp) < 0)
 852                        return -1;
 853                count -= p + 1 - buf;
 854                buf = p + 1;
 855                print = 1;
 856        }
 857        return 0;
 858}
 859
 860/*
 861 * '--color-words' algorithm can be described as:
 862 *
 863 *   1. collect a the minus/plus lines of a diff hunk, divided into
 864 *      minus-lines and plus-lines;
 865 *
 866 *   2. break both minus-lines and plus-lines into words and
 867 *      place them into two mmfile_t with one word for each line;
 868 *
 869 *   3. use xdiff to run diff on the two mmfile_t to get the words level diff;
 870 *
 871 * And for the common parts of the both file, we output the plus side text.
 872 * diff_words->current_plus is used to trace the current position of the plus file
 873 * which printed. diff_words->last_minus is used to trace the last minus word
 874 * printed.
 875 *
 876 * For '--graph' to work with '--color-words', we need to output the graph prefix
 877 * on each line of color words output. Generally, there are two conditions on
 878 * which we should output the prefix.
 879 *
 880 *   1. diff_words->last_minus == 0 &&
 881 *      diff_words->current_plus == diff_words->plus.text.ptr
 882 *
 883 *      that is: the plus text must start as a new line, and if there is no minus
 884 *      word printed, a graph prefix must be printed.
 885 *
 886 *   2. diff_words->current_plus > diff_words->plus.text.ptr &&
 887 *      *(diff_words->current_plus - 1) == '\n'
 888 *
 889 *      that is: a graph prefix must be printed following a '\n'
 890 */
 891static int color_words_output_graph_prefix(struct diff_words_data *diff_words)
 892{
 893        if ((diff_words->last_minus == 0 &&
 894                diff_words->current_plus == diff_words->plus.text.ptr) ||
 895                (diff_words->current_plus > diff_words->plus.text.ptr &&
 896                *(diff_words->current_plus - 1) == '\n')) {
 897                return 1;
 898        } else {
 899                return 0;
 900        }
 901}
 902
 903static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
 904{
 905        struct diff_words_data *diff_words = priv;
 906        struct diff_words_style *style = diff_words->style;
 907        int minus_first, minus_len, plus_first, plus_len;
 908        const char *minus_begin, *minus_end, *plus_begin, *plus_end;
 909        struct diff_options *opt = diff_words->opt;
 910        const char *line_prefix;
 911
 912        if (line[0] != '@' || parse_hunk_header(line, len,
 913                        &minus_first, &minus_len, &plus_first, &plus_len))
 914                return;
 915
 916        assert(opt);
 917        line_prefix = diff_line_prefix(opt);
 918
 919        /* POSIX requires that first be decremented by one if len == 0... */
 920        if (minus_len) {
 921                minus_begin = diff_words->minus.orig[minus_first].begin;
 922                minus_end =
 923                        diff_words->minus.orig[minus_first + minus_len - 1].end;
 924        } else
 925                minus_begin = minus_end =
 926                        diff_words->minus.orig[minus_first].end;
 927
 928        if (plus_len) {
 929                plus_begin = diff_words->plus.orig[plus_first].begin;
 930                plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
 931        } else
 932                plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
 933
 934        if (color_words_output_graph_prefix(diff_words)) {
 935                fputs(line_prefix, diff_words->opt->file);
 936        }
 937        if (diff_words->current_plus != plus_begin) {
 938                fn_out_diff_words_write_helper(diff_words->opt->file,
 939                                &style->ctx, style->newline,
 940                                plus_begin - diff_words->current_plus,
 941                                diff_words->current_plus, line_prefix);
 942                if (*(plus_begin - 1) == '\n')
 943                        fputs(line_prefix, diff_words->opt->file);
 944        }
 945        if (minus_begin != minus_end) {
 946                fn_out_diff_words_write_helper(diff_words->opt->file,
 947                                &style->old, style->newline,
 948                                minus_end - minus_begin, minus_begin,
 949                                line_prefix);
 950        }
 951        if (plus_begin != plus_end) {
 952                fn_out_diff_words_write_helper(diff_words->opt->file,
 953                                &style->new, style->newline,
 954                                plus_end - plus_begin, plus_begin,
 955                                line_prefix);
 956        }
 957
 958        diff_words->current_plus = plus_end;
 959        diff_words->last_minus = minus_first;
 960}
 961
 962/* This function starts looking at *begin, and returns 0 iff a word was found. */
 963static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
 964                int *begin, int *end)
 965{
 966        if (word_regex && *begin < buffer->size) {
 967                regmatch_t match[1];
 968                if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
 969                        char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
 970                                        '\n', match[0].rm_eo - match[0].rm_so);
 971                        *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
 972                        *begin += match[0].rm_so;
 973                        return *begin >= *end;
 974                }
 975                return -1;
 976        }
 977
 978        /* find the next word */
 979        while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
 980                (*begin)++;
 981        if (*begin >= buffer->size)
 982                return -1;
 983
 984        /* find the end of the word */
 985        *end = *begin + 1;
 986        while (*end < buffer->size && !isspace(buffer->ptr[*end]))
 987                (*end)++;
 988
 989        return 0;
 990}
 991
 992/*
 993 * This function splits the words in buffer->text, stores the list with
 994 * newline separator into out, and saves the offsets of the original words
 995 * in buffer->orig.
 996 */
 997static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
 998                regex_t *word_regex)
 999{
1000        int i, j;
1001        long alloc = 0;
1002
1003        out->size = 0;
1004        out->ptr = NULL;
1005
1006        /* fake an empty "0th" word */
1007        ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
1008        buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
1009        buffer->orig_nr = 1;
1010
1011        for (i = 0; i < buffer->text.size; i++) {
1012                if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
1013                        return;
1014
1015                /* store original boundaries */
1016                ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
1017                                buffer->orig_alloc);
1018                buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
1019                buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
1020                buffer->orig_nr++;
1021
1022                /* store one word */
1023                ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
1024                memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
1025                out->ptr[out->size + j - i] = '\n';
1026                out->size += j - i + 1;
1027
1028                i = j - 1;
1029        }
1030}
1031
1032/* this executes the word diff on the accumulated buffers */
1033static void diff_words_show(struct diff_words_data *diff_words)
1034{
1035        xpparam_t xpp;
1036        xdemitconf_t xecfg;
1037        mmfile_t minus, plus;
1038        struct diff_words_style *style = diff_words->style;
1039
1040        struct diff_options *opt = diff_words->opt;
1041        const char *line_prefix;
1042
1043        assert(opt);
1044        line_prefix = diff_line_prefix(opt);
1045
1046        /* special case: only removal */
1047        if (!diff_words->plus.text.size) {
1048                fputs(line_prefix, diff_words->opt->file);
1049                fn_out_diff_words_write_helper(diff_words->opt->file,
1050                        &style->old, style->newline,
1051                        diff_words->minus.text.size,
1052                        diff_words->minus.text.ptr, line_prefix);
1053                diff_words->minus.text.size = 0;
1054                return;
1055        }
1056
1057        diff_words->current_plus = diff_words->plus.text.ptr;
1058        diff_words->last_minus = 0;
1059
1060        memset(&xpp, 0, sizeof(xpp));
1061        memset(&xecfg, 0, sizeof(xecfg));
1062        diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
1063        diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
1064        xpp.flags = 0;
1065        /* as only the hunk header will be parsed, we need a 0-context */
1066        xecfg.ctxlen = 0;
1067        if (xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
1068                          &xpp, &xecfg))
1069                die("unable to generate word diff");
1070        free(minus.ptr);
1071        free(plus.ptr);
1072        if (diff_words->current_plus != diff_words->plus.text.ptr +
1073                        diff_words->plus.text.size) {
1074                if (color_words_output_graph_prefix(diff_words))
1075                        fputs(line_prefix, diff_words->opt->file);
1076                fn_out_diff_words_write_helper(diff_words->opt->file,
1077                        &style->ctx, style->newline,
1078                        diff_words->plus.text.ptr + diff_words->plus.text.size
1079                        - diff_words->current_plus, diff_words->current_plus,
1080                        line_prefix);
1081        }
1082        diff_words->minus.text.size = diff_words->plus.text.size = 0;
1083}
1084
1085/* In "color-words" mode, show word-diff of words accumulated in the buffer */
1086static void diff_words_flush(struct emit_callback *ecbdata)
1087{
1088        if (ecbdata->diff_words->minus.text.size ||
1089            ecbdata->diff_words->plus.text.size)
1090                diff_words_show(ecbdata->diff_words);
1091}
1092
1093static void diff_filespec_load_driver(struct diff_filespec *one)
1094{
1095        /* Use already-loaded driver */
1096        if (one->driver)
1097                return;
1098
1099        if (S_ISREG(one->mode))
1100                one->driver = userdiff_find_by_path(one->path);
1101
1102        /* Fallback to default settings */
1103        if (!one->driver)
1104                one->driver = userdiff_find_by_name("default");
1105}
1106
1107static const char *userdiff_word_regex(struct diff_filespec *one)
1108{
1109        diff_filespec_load_driver(one);
1110        return one->driver->word_regex;
1111}
1112
1113static void init_diff_words_data(struct emit_callback *ecbdata,
1114                                 struct diff_options *orig_opts,
1115                                 struct diff_filespec *one,
1116                                 struct diff_filespec *two)
1117{
1118        int i;
1119        struct diff_options *o = xmalloc(sizeof(struct diff_options));
1120        memcpy(o, orig_opts, sizeof(struct diff_options));
1121
1122        ecbdata->diff_words =
1123                xcalloc(1, sizeof(struct diff_words_data));
1124        ecbdata->diff_words->type = o->word_diff;
1125        ecbdata->diff_words->opt = o;
1126        if (!o->word_regex)
1127                o->word_regex = userdiff_word_regex(one);
1128        if (!o->word_regex)
1129                o->word_regex = userdiff_word_regex(two);
1130        if (!o->word_regex)
1131                o->word_regex = diff_word_regex_cfg;
1132        if (o->word_regex) {
1133                ecbdata->diff_words->word_regex = (regex_t *)
1134                        xmalloc(sizeof(regex_t));
1135                if (regcomp(ecbdata->diff_words->word_regex,
1136                            o->word_regex,
1137                            REG_EXTENDED | REG_NEWLINE))
1138                        die ("Invalid regular expression: %s",
1139                             o->word_regex);
1140        }
1141        for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1142                if (o->word_diff == diff_words_styles[i].type) {
1143                        ecbdata->diff_words->style =
1144                                &diff_words_styles[i];
1145                        break;
1146                }
1147        }
1148        if (want_color(o->use_color)) {
1149                struct diff_words_style *st = ecbdata->diff_words->style;
1150                st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1151                st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1152                st->ctx.color = diff_get_color_opt(o, DIFF_CONTEXT);
1153        }
1154}
1155
1156static void free_diff_words_data(struct emit_callback *ecbdata)
1157{
1158        if (ecbdata->diff_words) {
1159                diff_words_flush(ecbdata);
1160                free (ecbdata->diff_words->opt);
1161                free (ecbdata->diff_words->minus.text.ptr);
1162                free (ecbdata->diff_words->minus.orig);
1163                free (ecbdata->diff_words->plus.text.ptr);
1164                free (ecbdata->diff_words->plus.orig);
1165                if (ecbdata->diff_words->word_regex) {
1166                        regfree(ecbdata->diff_words->word_regex);
1167                        free(ecbdata->diff_words->word_regex);
1168                }
1169                free(ecbdata->diff_words);
1170                ecbdata->diff_words = NULL;
1171        }
1172}
1173
1174const char *diff_get_color(int diff_use_color, enum color_diff ix)
1175{
1176        if (want_color(diff_use_color))
1177                return diff_colors[ix];
1178        return "";
1179}
1180
1181const char *diff_line_prefix(struct diff_options *opt)
1182{
1183        struct strbuf *msgbuf;
1184        if (!opt->output_prefix)
1185                return "";
1186
1187        msgbuf = opt->output_prefix(opt, opt->output_prefix_data);
1188        return msgbuf->buf;
1189}
1190
1191static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
1192{
1193        const char *cp;
1194        unsigned long allot;
1195        size_t l = len;
1196
1197        if (ecb->truncate)
1198                return ecb->truncate(line, len);
1199        cp = line;
1200        allot = l;
1201        while (0 < l) {
1202                (void) utf8_width(&cp, &l);
1203                if (!cp)
1204                        break; /* truncated in the middle? */
1205        }
1206        return allot - l;
1207}
1208
1209static void find_lno(const char *line, struct emit_callback *ecbdata)
1210{
1211        const char *p;
1212        ecbdata->lno_in_preimage = 0;
1213        ecbdata->lno_in_postimage = 0;
1214        p = strchr(line, '-');
1215        if (!p)
1216                return; /* cannot happen */
1217        ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
1218        p = strchr(p, '+');
1219        if (!p)
1220                return; /* cannot happen */
1221        ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
1222}
1223
1224static void fn_out_consume(void *priv, char *line, unsigned long len)
1225{
1226        struct emit_callback *ecbdata = priv;
1227        const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
1228        const char *context = diff_get_color(ecbdata->color_diff, DIFF_CONTEXT);
1229        const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
1230        struct diff_options *o = ecbdata->opt;
1231        const char *line_prefix = diff_line_prefix(o);
1232
1233        if (ecbdata->header) {
1234                fprintf(ecbdata->opt->file, "%s", ecbdata->header->buf);
1235                strbuf_reset(ecbdata->header);
1236                ecbdata->header = NULL;
1237        }
1238        *(ecbdata->found_changesp) = 1;
1239
1240        if (ecbdata->label_path[0]) {
1241                const char *name_a_tab, *name_b_tab;
1242
1243                name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
1244                name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
1245
1246                fprintf(ecbdata->opt->file, "%s%s--- %s%s%s\n",
1247                        line_prefix, meta, ecbdata->label_path[0], reset, name_a_tab);
1248                fprintf(ecbdata->opt->file, "%s%s+++ %s%s%s\n",
1249                        line_prefix, meta, ecbdata->label_path[1], reset, name_b_tab);
1250                ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
1251        }
1252
1253        if (diff_suppress_blank_empty
1254            && len == 2 && line[0] == ' ' && line[1] == '\n') {
1255                line[0] = '\n';
1256                len = 1;
1257        }
1258
1259        if (line[0] == '@') {
1260                if (ecbdata->diff_words)
1261                        diff_words_flush(ecbdata);
1262                len = sane_truncate_line(ecbdata, line, len);
1263                find_lno(line, ecbdata);
1264                emit_hunk_header(ecbdata, line, len);
1265                if (line[len-1] != '\n')
1266                        putc('\n', ecbdata->opt->file);
1267                return;
1268        }
1269
1270        if (len < 1) {
1271                emit_line(ecbdata->opt, reset, reset, line, len);
1272                if (ecbdata->diff_words
1273                    && ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN)
1274                        fputs("~\n", ecbdata->opt->file);
1275                return;
1276        }
1277
1278        if (ecbdata->diff_words) {
1279                if (line[0] == '-') {
1280                        diff_words_append(line, len,
1281                                          &ecbdata->diff_words->minus);
1282                        return;
1283                } else if (line[0] == '+') {
1284                        diff_words_append(line, len,
1285                                          &ecbdata->diff_words->plus);
1286                        return;
1287                } else if (starts_with(line, "\\ ")) {
1288                        /*
1289                         * Eat the "no newline at eof" marker as if we
1290                         * saw a "+" or "-" line with nothing on it,
1291                         * and return without diff_words_flush() to
1292                         * defer processing. If this is the end of
1293                         * preimage, more "+" lines may come after it.
1294                         */
1295                        return;
1296                }
1297                diff_words_flush(ecbdata);
1298                if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
1299                        emit_line(ecbdata->opt, context, reset, line, len);
1300                        fputs("~\n", ecbdata->opt->file);
1301                } else {
1302                        /*
1303                         * Skip the prefix character, if any.  With
1304                         * diff_suppress_blank_empty, there may be
1305                         * none.
1306                         */
1307                        if (line[0] != '\n') {
1308                              line++;
1309                              len--;
1310                        }
1311                        emit_line(ecbdata->opt, context, reset, line, len);
1312                }
1313                return;
1314        }
1315
1316        switch (line[0]) {
1317        case '+':
1318                ecbdata->lno_in_postimage++;
1319                emit_add_line(reset, ecbdata, line + 1, len - 1);
1320                break;
1321        case '-':
1322                ecbdata->lno_in_preimage++;
1323                emit_del_line(reset, ecbdata, line + 1, len - 1);
1324                break;
1325        case ' ':
1326                ecbdata->lno_in_postimage++;
1327                ecbdata->lno_in_preimage++;
1328                emit_context_line(reset, ecbdata, line + 1, len - 1);
1329                break;
1330        default:
1331                /* incomplete line at the end */
1332                ecbdata->lno_in_preimage++;
1333                emit_line(ecbdata->opt,
1334                          diff_get_color(ecbdata->color_diff, DIFF_CONTEXT),
1335                          reset, line, len);
1336                break;
1337        }
1338}
1339
1340static char *pprint_rename(const char *a, const char *b)
1341{
1342        const char *old = a;
1343        const char *new = b;
1344        struct strbuf name = STRBUF_INIT;
1345        int pfx_length, sfx_length;
1346        int pfx_adjust_for_slash;
1347        int len_a = strlen(a);
1348        int len_b = strlen(b);
1349        int a_midlen, b_midlen;
1350        int qlen_a = quote_c_style(a, NULL, NULL, 0);
1351        int qlen_b = quote_c_style(b, NULL, NULL, 0);
1352
1353        if (qlen_a || qlen_b) {
1354                quote_c_style(a, &name, NULL, 0);
1355                strbuf_addstr(&name, " => ");
1356                quote_c_style(b, &name, NULL, 0);
1357                return strbuf_detach(&name, NULL);
1358        }
1359
1360        /* Find common prefix */
1361        pfx_length = 0;
1362        while (*old && *new && *old == *new) {
1363                if (*old == '/')
1364                        pfx_length = old - a + 1;
1365                old++;
1366                new++;
1367        }
1368
1369        /* Find common suffix */
1370        old = a + len_a;
1371        new = b + len_b;
1372        sfx_length = 0;
1373        /*
1374         * If there is a common prefix, it must end in a slash.  In
1375         * that case we let this loop run 1 into the prefix to see the
1376         * same slash.
1377         *
1378         * If there is no common prefix, we cannot do this as it would
1379         * underrun the input strings.
1380         */
1381        pfx_adjust_for_slash = (pfx_length ? 1 : 0);
1382        while (a + pfx_length - pfx_adjust_for_slash <= old &&
1383               b + pfx_length - pfx_adjust_for_slash <= new &&
1384               *old == *new) {
1385                if (*old == '/')
1386                        sfx_length = len_a - (old - a);
1387                old--;
1388                new--;
1389        }
1390
1391        /*
1392         * pfx{mid-a => mid-b}sfx
1393         * {pfx-a => pfx-b}sfx
1394         * pfx{sfx-a => sfx-b}
1395         * name-a => name-b
1396         */
1397        a_midlen = len_a - pfx_length - sfx_length;
1398        b_midlen = len_b - pfx_length - sfx_length;
1399        if (a_midlen < 0)
1400                a_midlen = 0;
1401        if (b_midlen < 0)
1402                b_midlen = 0;
1403
1404        strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
1405        if (pfx_length + sfx_length) {
1406                strbuf_add(&name, a, pfx_length);
1407                strbuf_addch(&name, '{');
1408        }
1409        strbuf_add(&name, a + pfx_length, a_midlen);
1410        strbuf_addstr(&name, " => ");
1411        strbuf_add(&name, b + pfx_length, b_midlen);
1412        if (pfx_length + sfx_length) {
1413                strbuf_addch(&name, '}');
1414                strbuf_add(&name, a + len_a - sfx_length, sfx_length);
1415        }
1416        return strbuf_detach(&name, NULL);
1417}
1418
1419struct diffstat_t {
1420        int nr;
1421        int alloc;
1422        struct diffstat_file {
1423                char *from_name;
1424                char *name;
1425                char *print_name;
1426                unsigned is_unmerged:1;
1427                unsigned is_binary:1;
1428                unsigned is_renamed:1;
1429                unsigned is_interesting:1;
1430                uintmax_t added, deleted;
1431        } **files;
1432};
1433
1434static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1435                                          const char *name_a,
1436                                          const char *name_b)
1437{
1438        struct diffstat_file *x;
1439        x = xcalloc(1, sizeof(*x));
1440        ALLOC_GROW(diffstat->files, diffstat->nr + 1, diffstat->alloc);
1441        diffstat->files[diffstat->nr++] = x;
1442        if (name_b) {
1443                x->from_name = xstrdup(name_a);
1444                x->name = xstrdup(name_b);
1445                x->is_renamed = 1;
1446        }
1447        else {
1448                x->from_name = NULL;
1449                x->name = xstrdup(name_a);
1450        }
1451        return x;
1452}
1453
1454static void diffstat_consume(void *priv, char *line, unsigned long len)
1455{
1456        struct diffstat_t *diffstat = priv;
1457        struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1458
1459        if (line[0] == '+')
1460                x->added++;
1461        else if (line[0] == '-')
1462                x->deleted++;
1463}
1464
1465const char mime_boundary_leader[] = "------------";
1466
1467static int scale_linear(int it, int width, int max_change)
1468{
1469        if (!it)
1470                return 0;
1471        /*
1472         * make sure that at least one '-' or '+' is printed if
1473         * there is any change to this path. The easiest way is to
1474         * scale linearly as if the alloted width is one column shorter
1475         * than it is, and then add 1 to the result.
1476         */
1477        return 1 + (it * (width - 1) / max_change);
1478}
1479
1480static void show_name(FILE *file,
1481                      const char *prefix, const char *name, int len)
1482{
1483        fprintf(file, " %s%-*s |", prefix, len, name);
1484}
1485
1486static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1487{
1488        if (cnt <= 0)
1489                return;
1490        fprintf(file, "%s", set);
1491        while (cnt--)
1492                putc(ch, file);
1493        fprintf(file, "%s", reset);
1494}
1495
1496static void fill_print_name(struct diffstat_file *file)
1497{
1498        char *pname;
1499
1500        if (file->print_name)
1501                return;
1502
1503        if (!file->is_renamed) {
1504                struct strbuf buf = STRBUF_INIT;
1505                if (quote_c_style(file->name, &buf, NULL, 0)) {
1506                        pname = strbuf_detach(&buf, NULL);
1507                } else {
1508                        pname = file->name;
1509                        strbuf_release(&buf);
1510                }
1511        } else {
1512                pname = pprint_rename(file->from_name, file->name);
1513        }
1514        file->print_name = pname;
1515}
1516
1517int print_stat_summary(FILE *fp, int files, int insertions, int deletions)
1518{
1519        struct strbuf sb = STRBUF_INIT;
1520        int ret;
1521
1522        if (!files) {
1523                assert(insertions == 0 && deletions == 0);
1524                return fprintf(fp, "%s\n", " 0 files changed");
1525        }
1526
1527        strbuf_addf(&sb,
1528                    (files == 1) ? " %d file changed" : " %d files changed",
1529                    files);
1530
1531        /*
1532         * For binary diff, the caller may want to print "x files
1533         * changed" with insertions == 0 && deletions == 0.
1534         *
1535         * Not omitting "0 insertions(+), 0 deletions(-)" in this case
1536         * is probably less confusing (i.e skip over "2 files changed
1537         * but nothing about added/removed lines? Is this a bug in Git?").
1538         */
1539        if (insertions || deletions == 0) {
1540                strbuf_addf(&sb,
1541                            (insertions == 1) ? ", %d insertion(+)" : ", %d insertions(+)",
1542                            insertions);
1543        }
1544
1545        if (deletions || insertions == 0) {
1546                strbuf_addf(&sb,
1547                            (deletions == 1) ? ", %d deletion(-)" : ", %d deletions(-)",
1548                            deletions);
1549        }
1550        strbuf_addch(&sb, '\n');
1551        ret = fputs(sb.buf, fp);
1552        strbuf_release(&sb);
1553        return ret;
1554}
1555
1556static void show_stats(struct diffstat_t *data, struct diff_options *options)
1557{
1558        int i, len, add, del, adds = 0, dels = 0;
1559        uintmax_t max_change = 0, max_len = 0;
1560        int total_files = data->nr, count;
1561        int width, name_width, graph_width, number_width = 0, bin_width = 0;
1562        const char *reset, *add_c, *del_c;
1563        const char *line_prefix = "";
1564        int extra_shown = 0;
1565
1566        if (data->nr == 0)
1567                return;
1568
1569        line_prefix = diff_line_prefix(options);
1570        count = options->stat_count ? options->stat_count : data->nr;
1571
1572        reset = diff_get_color_opt(options, DIFF_RESET);
1573        add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1574        del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1575
1576        /*
1577         * Find the longest filename and max number of changes
1578         */
1579        for (i = 0; (i < count) && (i < data->nr); i++) {
1580                struct diffstat_file *file = data->files[i];
1581                uintmax_t change = file->added + file->deleted;
1582
1583                if (!file->is_interesting && (change == 0)) {
1584                        count++; /* not shown == room for one more */
1585                        continue;
1586                }
1587                fill_print_name(file);
1588                len = strlen(file->print_name);
1589                if (max_len < len)
1590                        max_len = len;
1591
1592                if (file->is_unmerged) {
1593                        /* "Unmerged" is 8 characters */
1594                        bin_width = bin_width < 8 ? 8 : bin_width;
1595                        continue;
1596                }
1597                if (file->is_binary) {
1598                        /* "Bin XXX -> YYY bytes" */
1599                        int w = 14 + decimal_width(file->added)
1600                                + decimal_width(file->deleted);
1601                        bin_width = bin_width < w ? w : bin_width;
1602                        /* Display change counts aligned with "Bin" */
1603                        number_width = 3;
1604                        continue;
1605                }
1606
1607                if (max_change < change)
1608                        max_change = change;
1609        }
1610        count = i; /* where we can stop scanning in data->files[] */
1611
1612        /*
1613         * We have width = stat_width or term_columns() columns total.
1614         * We want a maximum of min(max_len, stat_name_width) for the name part.
1615         * We want a maximum of min(max_change, stat_graph_width) for the +- part.
1616         * We also need 1 for " " and 4 + decimal_width(max_change)
1617         * for " | NNNN " and one the empty column at the end, altogether
1618         * 6 + decimal_width(max_change).
1619         *
1620         * If there's not enough space, we will use the smaller of
1621         * stat_name_width (if set) and 5/8*width for the filename,
1622         * and the rest for constant elements + graph part, but no more
1623         * than stat_graph_width for the graph part.
1624         * (5/8 gives 50 for filename and 30 for the constant parts + graph
1625         * for the standard terminal size).
1626         *
1627         * In other words: stat_width limits the maximum width, and
1628         * stat_name_width fixes the maximum width of the filename,
1629         * and is also used to divide available columns if there
1630         * aren't enough.
1631         *
1632         * Binary files are displayed with "Bin XXX -> YYY bytes"
1633         * instead of the change count and graph. This part is treated
1634         * similarly to the graph part, except that it is not
1635         * "scaled". If total width is too small to accommodate the
1636         * guaranteed minimum width of the filename part and the
1637         * separators and this message, this message will "overflow"
1638         * making the line longer than the maximum width.
1639         */
1640
1641        if (options->stat_width == -1)
1642                width = term_columns() - options->output_prefix_length;
1643        else
1644                width = options->stat_width ? options->stat_width : 80;
1645        number_width = decimal_width(max_change) > number_width ?
1646                decimal_width(max_change) : number_width;
1647
1648        if (options->stat_graph_width == -1)
1649                options->stat_graph_width = diff_stat_graph_width;
1650
1651        /*
1652         * Guarantee 3/8*16==6 for the graph part
1653         * and 5/8*16==10 for the filename part
1654         */
1655        if (width < 16 + 6 + number_width)
1656                width = 16 + 6 + number_width;
1657
1658        /*
1659         * First assign sizes that are wanted, ignoring available width.
1660         * strlen("Bin XXX -> YYY bytes") == bin_width, and the part
1661         * starting from "XXX" should fit in graph_width.
1662         */
1663        graph_width = max_change + 4 > bin_width ? max_change : bin_width - 4;
1664        if (options->stat_graph_width &&
1665            options->stat_graph_width < graph_width)
1666                graph_width = options->stat_graph_width;
1667
1668        name_width = (options->stat_name_width > 0 &&
1669                      options->stat_name_width < max_len) ?
1670                options->stat_name_width : max_len;
1671
1672        /*
1673         * Adjust adjustable widths not to exceed maximum width
1674         */
1675        if (name_width + number_width + 6 + graph_width > width) {
1676                if (graph_width > width * 3/8 - number_width - 6) {
1677                        graph_width = width * 3/8 - number_width - 6;
1678                        if (graph_width < 6)
1679                                graph_width = 6;
1680                }
1681
1682                if (options->stat_graph_width &&
1683                    graph_width > options->stat_graph_width)
1684                        graph_width = options->stat_graph_width;
1685                if (name_width > width - number_width - 6 - graph_width)
1686                        name_width = width - number_width - 6 - graph_width;
1687                else
1688                        graph_width = width - number_width - 6 - name_width;
1689        }
1690
1691        /*
1692         * From here name_width is the width of the name area,
1693         * and graph_width is the width of the graph area.
1694         * max_change is used to scale graph properly.
1695         */
1696        for (i = 0; i < count; i++) {
1697                const char *prefix = "";
1698                struct diffstat_file *file = data->files[i];
1699                char *name = file->print_name;
1700                uintmax_t added = file->added;
1701                uintmax_t deleted = file->deleted;
1702                int name_len;
1703
1704                if (!file->is_interesting && (added + deleted == 0))
1705                        continue;
1706
1707                /*
1708                 * "scale" the filename
1709                 */
1710                len = name_width;
1711                name_len = strlen(name);
1712                if (name_width < name_len) {
1713                        char *slash;
1714                        prefix = "...";
1715                        len -= 3;
1716                        name += name_len - len;
1717                        slash = strchr(name, '/');
1718                        if (slash)
1719                                name = slash;
1720                }
1721
1722                if (file->is_binary) {
1723                        fprintf(options->file, "%s", line_prefix);
1724                        show_name(options->file, prefix, name, len);
1725                        fprintf(options->file, " %*s", number_width, "Bin");
1726                        if (!added && !deleted) {
1727                                putc('\n', options->file);
1728                                continue;
1729                        }
1730                        fprintf(options->file, " %s%"PRIuMAX"%s",
1731                                del_c, deleted, reset);
1732                        fprintf(options->file, " -> ");
1733                        fprintf(options->file, "%s%"PRIuMAX"%s",
1734                                add_c, added, reset);
1735                        fprintf(options->file, " bytes");
1736                        fprintf(options->file, "\n");
1737                        continue;
1738                }
1739                else if (file->is_unmerged) {
1740                        fprintf(options->file, "%s", line_prefix);
1741                        show_name(options->file, prefix, name, len);
1742                        fprintf(options->file, " Unmerged\n");
1743                        continue;
1744                }
1745
1746                /*
1747                 * scale the add/delete
1748                 */
1749                add = added;
1750                del = deleted;
1751
1752                if (graph_width <= max_change) {
1753                        int total = scale_linear(add + del, graph_width, max_change);
1754                        if (total < 2 && add && del)
1755                                /* width >= 2 due to the sanity check */
1756                                total = 2;
1757                        if (add < del) {
1758                                add = scale_linear(add, graph_width, max_change);
1759                                del = total - add;
1760                        } else {
1761                                del = scale_linear(del, graph_width, max_change);
1762                                add = total - del;
1763                        }
1764                }
1765                fprintf(options->file, "%s", line_prefix);
1766                show_name(options->file, prefix, name, len);
1767                fprintf(options->file, " %*"PRIuMAX"%s",
1768                        number_width, added + deleted,
1769                        added + deleted ? " " : "");
1770                show_graph(options->file, '+', add, add_c, reset);
1771                show_graph(options->file, '-', del, del_c, reset);
1772                fprintf(options->file, "\n");
1773        }
1774
1775        for (i = 0; i < data->nr; i++) {
1776                struct diffstat_file *file = data->files[i];
1777                uintmax_t added = file->added;
1778                uintmax_t deleted = file->deleted;
1779
1780                if (file->is_unmerged ||
1781                    (!file->is_interesting && (added + deleted == 0))) {
1782                        total_files--;
1783                        continue;
1784                }
1785
1786                if (!file->is_binary) {
1787                        adds += added;
1788                        dels += deleted;
1789                }
1790                if (i < count)
1791                        continue;
1792                if (!extra_shown)
1793                        fprintf(options->file, "%s ...\n", line_prefix);
1794                extra_shown = 1;
1795        }
1796        fprintf(options->file, "%s", line_prefix);
1797        print_stat_summary(options->file, total_files, adds, dels);
1798}
1799
1800static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1801{
1802        int i, adds = 0, dels = 0, total_files = data->nr;
1803
1804        if (data->nr == 0)
1805                return;
1806
1807        for (i = 0; i < data->nr; i++) {
1808                int added = data->files[i]->added;
1809                int deleted= data->files[i]->deleted;
1810
1811                if (data->files[i]->is_unmerged ||
1812                    (!data->files[i]->is_interesting && (added + deleted == 0))) {
1813                        total_files--;
1814                } else if (!data->files[i]->is_binary) { /* don't count bytes */
1815                        adds += added;
1816                        dels += deleted;
1817                }
1818        }
1819        fprintf(options->file, "%s", diff_line_prefix(options));
1820        print_stat_summary(options->file, total_files, adds, dels);
1821}
1822
1823static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1824{
1825        int i;
1826
1827        if (data->nr == 0)
1828                return;
1829
1830        for (i = 0; i < data->nr; i++) {
1831                struct diffstat_file *file = data->files[i];
1832
1833                fprintf(options->file, "%s", diff_line_prefix(options));
1834
1835                if (file->is_binary)
1836                        fprintf(options->file, "-\t-\t");
1837                else
1838                        fprintf(options->file,
1839                                "%"PRIuMAX"\t%"PRIuMAX"\t",
1840                                file->added, file->deleted);
1841                if (options->line_termination) {
1842                        fill_print_name(file);
1843                        if (!file->is_renamed)
1844                                write_name_quoted(file->name, options->file,
1845                                                  options->line_termination);
1846                        else {
1847                                fputs(file->print_name, options->file);
1848                                putc(options->line_termination, options->file);
1849                        }
1850                } else {
1851                        if (file->is_renamed) {
1852                                putc('\0', options->file);
1853                                write_name_quoted(file->from_name, options->file, '\0');
1854                        }
1855                        write_name_quoted(file->name, options->file, '\0');
1856                }
1857        }
1858}
1859
1860struct dirstat_file {
1861        const char *name;
1862        unsigned long changed;
1863};
1864
1865struct dirstat_dir {
1866        struct dirstat_file *files;
1867        int alloc, nr, permille, cumulative;
1868};
1869
1870static long gather_dirstat(struct diff_options *opt, struct dirstat_dir *dir,
1871                unsigned long changed, const char *base, int baselen)
1872{
1873        unsigned long this_dir = 0;
1874        unsigned int sources = 0;
1875        const char *line_prefix = diff_line_prefix(opt);
1876
1877        while (dir->nr) {
1878                struct dirstat_file *f = dir->files;
1879                int namelen = strlen(f->name);
1880                unsigned long this;
1881                char *slash;
1882
1883                if (namelen < baselen)
1884                        break;
1885                if (memcmp(f->name, base, baselen))
1886                        break;
1887                slash = strchr(f->name + baselen, '/');
1888                if (slash) {
1889                        int newbaselen = slash + 1 - f->name;
1890                        this = gather_dirstat(opt, dir, changed, f->name, newbaselen);
1891                        sources++;
1892                } else {
1893                        this = f->changed;
1894                        dir->files++;
1895                        dir->nr--;
1896                        sources += 2;
1897                }
1898                this_dir += this;
1899        }
1900
1901        /*
1902         * We don't report dirstat's for
1903         *  - the top level
1904         *  - or cases where everything came from a single directory
1905         *    under this directory (sources == 1).
1906         */
1907        if (baselen && sources != 1) {
1908                if (this_dir) {
1909                        int permille = this_dir * 1000 / changed;
1910                        if (permille >= dir->permille) {
1911                                fprintf(opt->file, "%s%4d.%01d%% %.*s\n", line_prefix,
1912                                        permille / 10, permille % 10, baselen, base);
1913                                if (!dir->cumulative)
1914                                        return 0;
1915                        }
1916                }
1917        }
1918        return this_dir;
1919}
1920
1921static int dirstat_compare(const void *_a, const void *_b)
1922{
1923        const struct dirstat_file *a = _a;
1924        const struct dirstat_file *b = _b;
1925        return strcmp(a->name, b->name);
1926}
1927
1928static void show_dirstat(struct diff_options *options)
1929{
1930        int i;
1931        unsigned long changed;
1932        struct dirstat_dir dir;
1933        struct diff_queue_struct *q = &diff_queued_diff;
1934
1935        dir.files = NULL;
1936        dir.alloc = 0;
1937        dir.nr = 0;
1938        dir.permille = options->dirstat_permille;
1939        dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1940
1941        changed = 0;
1942        for (i = 0; i < q->nr; i++) {
1943                struct diff_filepair *p = q->queue[i];
1944                const char *name;
1945                unsigned long copied, added, damage;
1946                int content_changed;
1947
1948                name = p->two->path ? p->two->path : p->one->path;
1949
1950                if (p->one->sha1_valid && p->two->sha1_valid)
1951                        content_changed = hashcmp(p->one->sha1, p->two->sha1);
1952                else
1953                        content_changed = 1;
1954
1955                if (!content_changed) {
1956                        /*
1957                         * The SHA1 has not changed, so pre-/post-content is
1958                         * identical. We can therefore skip looking at the
1959                         * file contents altogether.
1960                         */
1961                        damage = 0;
1962                        goto found_damage;
1963                }
1964
1965                if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE)) {
1966                        /*
1967                         * In --dirstat-by-file mode, we don't really need to
1968                         * look at the actual file contents at all.
1969                         * The fact that the SHA1 changed is enough for us to
1970                         * add this file to the list of results
1971                         * (with each file contributing equal damage).
1972                         */
1973                        damage = 1;
1974                        goto found_damage;
1975                }
1976
1977                if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1978                        diff_populate_filespec(p->one, 0);
1979                        diff_populate_filespec(p->two, 0);
1980                        diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1981                                               &copied, &added);
1982                        diff_free_filespec_data(p->one);
1983                        diff_free_filespec_data(p->two);
1984                } else if (DIFF_FILE_VALID(p->one)) {
1985                        diff_populate_filespec(p->one, CHECK_SIZE_ONLY);
1986                        copied = added = 0;
1987                        diff_free_filespec_data(p->one);
1988                } else if (DIFF_FILE_VALID(p->two)) {
1989                        diff_populate_filespec(p->two, CHECK_SIZE_ONLY);
1990                        copied = 0;
1991                        added = p->two->size;
1992                        diff_free_filespec_data(p->two);
1993                } else
1994                        continue;
1995
1996                /*
1997                 * Original minus copied is the removed material,
1998                 * added is the new material.  They are both damages
1999                 * made to the preimage.
2000                 * If the resulting damage is zero, we know that
2001                 * diffcore_count_changes() considers the two entries to
2002                 * be identical, but since content_changed is true, we
2003                 * know that there must have been _some_ kind of change,
2004                 * so we force all entries to have damage > 0.
2005                 */
2006                damage = (p->one->size - copied) + added;
2007                if (!damage)
2008                        damage = 1;
2009
2010found_damage:
2011                ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2012                dir.files[dir.nr].name = name;
2013                dir.files[dir.nr].changed = damage;
2014                changed += damage;
2015                dir.nr++;
2016        }
2017
2018        /* This can happen even with many files, if everything was renames */
2019        if (!changed)
2020                return;
2021
2022        /* Show all directories with more than x% of the changes */
2023        qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
2024        gather_dirstat(options, &dir, changed, "", 0);
2025}
2026
2027static void show_dirstat_by_line(struct diffstat_t *data, struct diff_options *options)
2028{
2029        int i;
2030        unsigned long changed;
2031        struct dirstat_dir dir;
2032
2033        if (data->nr == 0)
2034                return;
2035
2036        dir.files = NULL;
2037        dir.alloc = 0;
2038        dir.nr = 0;
2039        dir.permille = options->dirstat_permille;
2040        dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
2041
2042        changed = 0;
2043        for (i = 0; i < data->nr; i++) {
2044                struct diffstat_file *file = data->files[i];
2045                unsigned long damage = file->added + file->deleted;
2046                if (file->is_binary)
2047                        /*
2048                         * binary files counts bytes, not lines. Must find some
2049                         * way to normalize binary bytes vs. textual lines.
2050                         * The following heuristic assumes that there are 64
2051                         * bytes per "line".
2052                         * This is stupid and ugly, but very cheap...
2053                         */
2054                        damage = (damage + 63) / 64;
2055                ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
2056                dir.files[dir.nr].name = file->name;
2057                dir.files[dir.nr].changed = damage;
2058                changed += damage;
2059                dir.nr++;
2060        }
2061
2062        /* This can happen even with many files, if everything was renames */
2063        if (!changed)
2064                return;
2065
2066        /* Show all directories with more than x% of the changes */
2067        qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
2068        gather_dirstat(options, &dir, changed, "", 0);
2069}
2070
2071static void free_diffstat_info(struct diffstat_t *diffstat)
2072{
2073        int i;
2074        for (i = 0; i < diffstat->nr; i++) {
2075                struct diffstat_file *f = diffstat->files[i];
2076                if (f->name != f->print_name)
2077                        free(f->print_name);
2078                free(f->name);
2079                free(f->from_name);
2080                free(f);
2081        }
2082        free(diffstat->files);
2083}
2084
2085struct checkdiff_t {
2086        const char *filename;
2087        int lineno;
2088        int conflict_marker_size;
2089        struct diff_options *o;
2090        unsigned ws_rule;
2091        unsigned status;
2092};
2093
2094static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
2095{
2096        char firstchar;
2097        int cnt;
2098
2099        if (len < marker_size + 1)
2100                return 0;
2101        firstchar = line[0];
2102        switch (firstchar) {
2103        case '=': case '>': case '<': case '|':
2104                break;
2105        default:
2106                return 0;
2107        }
2108        for (cnt = 1; cnt < marker_size; cnt++)
2109                if (line[cnt] != firstchar)
2110                        return 0;
2111        /* line[1] thru line[marker_size-1] are same as firstchar */
2112        if (len < marker_size + 1 || !isspace(line[marker_size]))
2113                return 0;
2114        return 1;
2115}
2116
2117static void checkdiff_consume(void *priv, char *line, unsigned long len)
2118{
2119        struct checkdiff_t *data = priv;
2120        int marker_size = data->conflict_marker_size;
2121        const char *ws = diff_get_color(data->o->use_color, DIFF_WHITESPACE);
2122        const char *reset = diff_get_color(data->o->use_color, DIFF_RESET);
2123        const char *set = diff_get_color(data->o->use_color, DIFF_FILE_NEW);
2124        char *err;
2125        const char *line_prefix;
2126
2127        assert(data->o);
2128        line_prefix = diff_line_prefix(data->o);
2129
2130        if (line[0] == '+') {
2131                unsigned bad;
2132                data->lineno++;
2133                if (is_conflict_marker(line + 1, marker_size, len - 1)) {
2134                        data->status |= 1;
2135                        fprintf(data->o->file,
2136                                "%s%s:%d: leftover conflict marker\n",
2137                                line_prefix, data->filename, data->lineno);
2138                }
2139                bad = ws_check(line + 1, len - 1, data->ws_rule);
2140                if (!bad)
2141                        return;
2142                data->status |= bad;
2143                err = whitespace_error_string(bad);
2144                fprintf(data->o->file, "%s%s:%d: %s.\n",
2145                        line_prefix, data->filename, data->lineno, err);
2146                free(err);
2147                emit_line(data->o, set, reset, line, 1);
2148                ws_check_emit(line + 1, len - 1, data->ws_rule,
2149                              data->o->file, set, reset, ws);
2150        } else if (line[0] == ' ') {
2151                data->lineno++;
2152        } else if (line[0] == '@') {
2153                char *plus = strchr(line, '+');
2154                if (plus)
2155                        data->lineno = strtol(plus, NULL, 10) - 1;
2156                else
2157                        die("invalid diff");
2158        }
2159}
2160
2161static unsigned char *deflate_it(char *data,
2162                                 unsigned long size,
2163                                 unsigned long *result_size)
2164{
2165        int bound;
2166        unsigned char *deflated;
2167        git_zstream stream;
2168
2169        git_deflate_init(&stream, zlib_compression_level);
2170        bound = git_deflate_bound(&stream, size);
2171        deflated = xmalloc(bound);
2172        stream.next_out = deflated;
2173        stream.avail_out = bound;
2174
2175        stream.next_in = (unsigned char *)data;
2176        stream.avail_in = size;
2177        while (git_deflate(&stream, Z_FINISH) == Z_OK)
2178                ; /* nothing */
2179        git_deflate_end(&stream);
2180        *result_size = stream.total_out;
2181        return deflated;
2182}
2183
2184static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two,
2185                                  const char *prefix)
2186{
2187        void *cp;
2188        void *delta;
2189        void *deflated;
2190        void *data;
2191        unsigned long orig_size;
2192        unsigned long delta_size;
2193        unsigned long deflate_size;
2194        unsigned long data_size;
2195
2196        /* We could do deflated delta, or we could do just deflated two,
2197         * whichever is smaller.
2198         */
2199        delta = NULL;
2200        deflated = deflate_it(two->ptr, two->size, &deflate_size);
2201        if (one->size && two->size) {
2202                delta = diff_delta(one->ptr, one->size,
2203                                   two->ptr, two->size,
2204                                   &delta_size, deflate_size);
2205                if (delta) {
2206                        void *to_free = delta;
2207                        orig_size = delta_size;
2208                        delta = deflate_it(delta, delta_size, &delta_size);
2209                        free(to_free);
2210                }
2211        }
2212
2213        if (delta && delta_size < deflate_size) {
2214                fprintf(file, "%sdelta %lu\n", prefix, orig_size);
2215                free(deflated);
2216                data = delta;
2217                data_size = delta_size;
2218        }
2219        else {
2220                fprintf(file, "%sliteral %lu\n", prefix, two->size);
2221                free(delta);
2222                data = deflated;
2223                data_size = deflate_size;
2224        }
2225
2226        /* emit data encoded in base85 */
2227        cp = data;
2228        while (data_size) {
2229                int bytes = (52 < data_size) ? 52 : data_size;
2230                char line[70];
2231                data_size -= bytes;
2232                if (bytes <= 26)
2233                        line[0] = bytes + 'A' - 1;
2234                else
2235                        line[0] = bytes - 26 + 'a' - 1;
2236                encode_85(line + 1, cp, bytes);
2237                cp = (char *) cp + bytes;
2238                fprintf(file, "%s", prefix);
2239                fputs(line, file);
2240                fputc('\n', file);
2241        }
2242        fprintf(file, "%s\n", prefix);
2243        free(data);
2244}
2245
2246static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two,
2247                             const char *prefix)
2248{
2249        fprintf(file, "%sGIT binary patch\n", prefix);
2250        emit_binary_diff_body(file, one, two, prefix);
2251        emit_binary_diff_body(file, two, one, prefix);
2252}
2253
2254int diff_filespec_is_binary(struct diff_filespec *one)
2255{
2256        if (one->is_binary == -1) {
2257                diff_filespec_load_driver(one);
2258                if (one->driver->binary != -1)
2259                        one->is_binary = one->driver->binary;
2260                else {
2261                        if (!one->data && DIFF_FILE_VALID(one))
2262                                diff_populate_filespec(one, CHECK_BINARY);
2263                        if (one->is_binary == -1 && one->data)
2264                                one->is_binary = buffer_is_binary(one->data,
2265                                                one->size);
2266                        if (one->is_binary == -1)
2267                                one->is_binary = 0;
2268                }
2269        }
2270        return one->is_binary;
2271}
2272
2273static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
2274{
2275        diff_filespec_load_driver(one);
2276        return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
2277}
2278
2279void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
2280{
2281        if (!options->a_prefix)
2282                options->a_prefix = a;
2283        if (!options->b_prefix)
2284                options->b_prefix = b;
2285}
2286
2287struct userdiff_driver *get_textconv(struct diff_filespec *one)
2288{
2289        if (!DIFF_FILE_VALID(one))
2290                return NULL;
2291
2292        diff_filespec_load_driver(one);
2293        return userdiff_get_textconv(one->driver);
2294}
2295
2296static void builtin_diff(const char *name_a,
2297                         const char *name_b,
2298                         struct diff_filespec *one,
2299                         struct diff_filespec *two,
2300                         const char *xfrm_msg,
2301                         int must_show_header,
2302                         struct diff_options *o,
2303                         int complete_rewrite)
2304{
2305        mmfile_t mf1, mf2;
2306        const char *lbl[2];
2307        char *a_one, *b_two;
2308        const char *meta = diff_get_color_opt(o, DIFF_METAINFO);
2309        const char *reset = diff_get_color_opt(o, DIFF_RESET);
2310        const char *a_prefix, *b_prefix;
2311        struct userdiff_driver *textconv_one = NULL;
2312        struct userdiff_driver *textconv_two = NULL;
2313        struct strbuf header = STRBUF_INIT;
2314        const char *line_prefix = diff_line_prefix(o);
2315
2316        if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
2317                        (!one->mode || S_ISGITLINK(one->mode)) &&
2318                        (!two->mode || S_ISGITLINK(two->mode))) {
2319                const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
2320                const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
2321                show_submodule_summary(o->file, one->path ? one->path : two->path,
2322                                line_prefix,
2323                                one->sha1, two->sha1, two->dirty_submodule,
2324                                meta, del, add, reset);
2325                return;
2326        }
2327
2328        if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
2329                textconv_one = get_textconv(one);
2330                textconv_two = get_textconv(two);
2331        }
2332
2333        diff_set_mnemonic_prefix(o, "a/", "b/");
2334        if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
2335                a_prefix = o->b_prefix;
2336                b_prefix = o->a_prefix;
2337        } else {
2338                a_prefix = o->a_prefix;
2339                b_prefix = o->b_prefix;
2340        }
2341
2342        /* Never use a non-valid filename anywhere if at all possible */
2343        name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
2344        name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
2345
2346        a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
2347        b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
2348        lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
2349        lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
2350        strbuf_addf(&header, "%s%sdiff --git %s %s%s\n", line_prefix, meta, a_one, b_two, reset);
2351        if (lbl[0][0] == '/') {
2352                /* /dev/null */
2353                strbuf_addf(&header, "%s%snew file mode %06o%s\n", line_prefix, meta, two->mode, reset);
2354                if (xfrm_msg)
2355                        strbuf_addstr(&header, xfrm_msg);
2356                must_show_header = 1;
2357        }
2358        else if (lbl[1][0] == '/') {
2359                strbuf_addf(&header, "%s%sdeleted file mode %06o%s\n", line_prefix, meta, one->mode, reset);
2360                if (xfrm_msg)
2361                        strbuf_addstr(&header, xfrm_msg);
2362                must_show_header = 1;
2363        }
2364        else {
2365                if (one->mode != two->mode) {
2366                        strbuf_addf(&header, "%s%sold mode %06o%s\n", line_prefix, meta, one->mode, reset);
2367                        strbuf_addf(&header, "%s%snew mode %06o%s\n", line_prefix, meta, two->mode, reset);
2368                        must_show_header = 1;
2369                }
2370                if (xfrm_msg)
2371                        strbuf_addstr(&header, xfrm_msg);
2372
2373                /*
2374                 * we do not run diff between different kind
2375                 * of objects.
2376                 */
2377                if ((one->mode ^ two->mode) & S_IFMT)
2378                        goto free_ab_and_return;
2379                if (complete_rewrite &&
2380                    (textconv_one || !diff_filespec_is_binary(one)) &&
2381                    (textconv_two || !diff_filespec_is_binary(two))) {
2382                        fprintf(o->file, "%s", header.buf);
2383                        strbuf_reset(&header);
2384                        emit_rewrite_diff(name_a, name_b, one, two,
2385                                                textconv_one, textconv_two, o);
2386                        o->found_changes = 1;
2387                        goto free_ab_and_return;
2388                }
2389        }
2390
2391        if (o->irreversible_delete && lbl[1][0] == '/') {
2392                fprintf(o->file, "%s", header.buf);
2393                strbuf_reset(&header);
2394                goto free_ab_and_return;
2395        } else if (!DIFF_OPT_TST(o, TEXT) &&
2396            ( (!textconv_one && diff_filespec_is_binary(one)) ||
2397              (!textconv_two && diff_filespec_is_binary(two)) )) {
2398                if (!one->data && !two->data &&
2399                    S_ISREG(one->mode) && S_ISREG(two->mode) &&
2400                    !DIFF_OPT_TST(o, BINARY)) {
2401                        if (!hashcmp(one->sha1, two->sha1)) {
2402                                if (must_show_header)
2403                                        fprintf(o->file, "%s", header.buf);
2404                                goto free_ab_and_return;
2405                        }
2406                        fprintf(o->file, "%s", header.buf);
2407                        fprintf(o->file, "%sBinary files %s and %s differ\n",
2408                                line_prefix, lbl[0], lbl[1]);
2409                        goto free_ab_and_return;
2410                }
2411                if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2412                        die("unable to read files to diff");
2413                /* Quite common confusing case */
2414                if (mf1.size == mf2.size &&
2415                    !memcmp(mf1.ptr, mf2.ptr, mf1.size)) {
2416                        if (must_show_header)
2417                                fprintf(o->file, "%s", header.buf);
2418                        goto free_ab_and_return;
2419                }
2420                fprintf(o->file, "%s", header.buf);
2421                strbuf_reset(&header);
2422                if (DIFF_OPT_TST(o, BINARY))
2423                        emit_binary_diff(o->file, &mf1, &mf2, line_prefix);
2424                else
2425                        fprintf(o->file, "%sBinary files %s and %s differ\n",
2426                                line_prefix, lbl[0], lbl[1]);
2427                o->found_changes = 1;
2428        } else {
2429                /* Crazy xdl interfaces.. */
2430                const char *diffopts = getenv("GIT_DIFF_OPTS");
2431                const char *v;
2432                xpparam_t xpp;
2433                xdemitconf_t xecfg;
2434                struct emit_callback ecbdata;
2435                const struct userdiff_funcname *pe;
2436
2437                if (must_show_header) {
2438                        fprintf(o->file, "%s", header.buf);
2439                        strbuf_reset(&header);
2440                }
2441
2442                mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
2443                mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
2444
2445                pe = diff_funcname_pattern(one);
2446                if (!pe)
2447                        pe = diff_funcname_pattern(two);
2448
2449                memset(&xpp, 0, sizeof(xpp));
2450                memset(&xecfg, 0, sizeof(xecfg));
2451                memset(&ecbdata, 0, sizeof(ecbdata));
2452                ecbdata.label_path = lbl;
2453                ecbdata.color_diff = want_color(o->use_color);
2454                ecbdata.found_changesp = &o->found_changes;
2455                ecbdata.ws_rule = whitespace_rule(name_b);
2456                if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
2457                        check_blank_at_eof(&mf1, &mf2, &ecbdata);
2458                ecbdata.opt = o;
2459                ecbdata.header = header.len ? &header : NULL;
2460                xpp.flags = o->xdl_opts;
2461                xecfg.ctxlen = o->context;
2462                xecfg.interhunkctxlen = o->interhunkcontext;
2463                xecfg.flags = XDL_EMIT_FUNCNAMES;
2464                if (DIFF_OPT_TST(o, FUNCCONTEXT))
2465                        xecfg.flags |= XDL_EMIT_FUNCCONTEXT;
2466                if (pe)
2467                        xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
2468                if (!diffopts)
2469                        ;
2470                else if (skip_prefix(diffopts, "--unified=", &v))
2471                        xecfg.ctxlen = strtoul(v, NULL, 10);
2472                else if (skip_prefix(diffopts, "-u", &v))
2473                        xecfg.ctxlen = strtoul(v, NULL, 10);
2474                if (o->word_diff)
2475                        init_diff_words_data(&ecbdata, o, one, two);
2476                if (xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
2477                                  &xpp, &xecfg))
2478                        die("unable to generate diff for %s", one->path);
2479                if (o->word_diff)
2480                        free_diff_words_data(&ecbdata);
2481                if (textconv_one)
2482                        free(mf1.ptr);
2483                if (textconv_two)
2484                        free(mf2.ptr);
2485                xdiff_clear_find_func(&xecfg);
2486        }
2487
2488 free_ab_and_return:
2489        strbuf_release(&header);
2490        diff_free_filespec_data(one);
2491        diff_free_filespec_data(two);
2492        free(a_one);
2493        free(b_two);
2494        return;
2495}
2496
2497static void builtin_diffstat(const char *name_a, const char *name_b,
2498                             struct diff_filespec *one,
2499                             struct diff_filespec *two,
2500                             struct diffstat_t *diffstat,
2501                             struct diff_options *o,
2502                             struct diff_filepair *p)
2503{
2504        mmfile_t mf1, mf2;
2505        struct diffstat_file *data;
2506        int same_contents;
2507        int complete_rewrite = 0;
2508
2509        if (!DIFF_PAIR_UNMERGED(p)) {
2510                if (p->status == DIFF_STATUS_MODIFIED && p->score)
2511                        complete_rewrite = 1;
2512        }
2513
2514        data = diffstat_add(diffstat, name_a, name_b);
2515        data->is_interesting = p->status != DIFF_STATUS_UNKNOWN;
2516
2517        if (!one || !two) {
2518                data->is_unmerged = 1;
2519                return;
2520        }
2521
2522        same_contents = !hashcmp(one->sha1, two->sha1);
2523
2524        if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
2525                data->is_binary = 1;
2526                if (same_contents) {
2527                        data->added = 0;
2528                        data->deleted = 0;
2529                } else {
2530                        data->added = diff_filespec_size(two);
2531                        data->deleted = diff_filespec_size(one);
2532                }
2533        }
2534
2535        else if (complete_rewrite) {
2536                diff_populate_filespec(one, 0);
2537                diff_populate_filespec(two, 0);
2538                data->deleted = count_lines(one->data, one->size);
2539                data->added = count_lines(two->data, two->size);
2540        }
2541
2542        else if (!same_contents) {
2543                /* Crazy xdl interfaces.. */
2544                xpparam_t xpp;
2545                xdemitconf_t xecfg;
2546
2547                if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2548                        die("unable to read files to diff");
2549
2550                memset(&xpp, 0, sizeof(xpp));
2551                memset(&xecfg, 0, sizeof(xecfg));
2552                xpp.flags = o->xdl_opts;
2553                xecfg.ctxlen = o->context;
2554                xecfg.interhunkctxlen = o->interhunkcontext;
2555                if (xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
2556                                  &xpp, &xecfg))
2557                        die("unable to generate diffstat for %s", one->path);
2558        }
2559
2560        diff_free_filespec_data(one);
2561        diff_free_filespec_data(two);
2562}
2563
2564static void builtin_checkdiff(const char *name_a, const char *name_b,
2565                              const char *attr_path,
2566                              struct diff_filespec *one,
2567                              struct diff_filespec *two,
2568                              struct diff_options *o)
2569{
2570        mmfile_t mf1, mf2;
2571        struct checkdiff_t data;
2572
2573        if (!two)
2574                return;
2575
2576        memset(&data, 0, sizeof(data));
2577        data.filename = name_b ? name_b : name_a;
2578        data.lineno = 0;
2579        data.o = o;
2580        data.ws_rule = whitespace_rule(attr_path);
2581        data.conflict_marker_size = ll_merge_marker_size(attr_path);
2582
2583        if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
2584                die("unable to read files to diff");
2585
2586        /*
2587         * All the other codepaths check both sides, but not checking
2588         * the "old" side here is deliberate.  We are checking the newly
2589         * introduced changes, and as long as the "new" side is text, we
2590         * can and should check what it introduces.
2591         */
2592        if (diff_filespec_is_binary(two))
2593                goto free_and_return;
2594        else {
2595                /* Crazy xdl interfaces.. */
2596                xpparam_t xpp;
2597                xdemitconf_t xecfg;
2598
2599                memset(&xpp, 0, sizeof(xpp));
2600                memset(&xecfg, 0, sizeof(xecfg));
2601                xecfg.ctxlen = 1; /* at least one context line */
2602                xpp.flags = 0;
2603                if (xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
2604                                  &xpp, &xecfg))
2605                        die("unable to generate checkdiff for %s", one->path);
2606
2607                if (data.ws_rule & WS_BLANK_AT_EOF) {
2608                        struct emit_callback ecbdata;
2609                        int blank_at_eof;
2610
2611                        ecbdata.ws_rule = data.ws_rule;
2612                        check_blank_at_eof(&mf1, &mf2, &ecbdata);
2613                        blank_at_eof = ecbdata.blank_at_eof_in_postimage;
2614
2615                        if (blank_at_eof) {
2616                                static char *err;
2617                                if (!err)
2618                                        err = whitespace_error_string(WS_BLANK_AT_EOF);
2619                                fprintf(o->file, "%s:%d: %s.\n",
2620                                        data.filename, blank_at_eof, err);
2621                                data.status = 1; /* report errors */
2622                        }
2623                }
2624        }
2625 free_and_return:
2626        diff_free_filespec_data(one);
2627        diff_free_filespec_data(two);
2628        if (data.status)
2629                DIFF_OPT_SET(o, CHECK_FAILED);
2630}
2631
2632struct diff_filespec *alloc_filespec(const char *path)
2633{
2634        struct diff_filespec *spec;
2635
2636        FLEXPTR_ALLOC_STR(spec, path, path);
2637        spec->count = 1;
2638        spec->is_binary = -1;
2639        return spec;
2640}
2641
2642void free_filespec(struct diff_filespec *spec)
2643{
2644        if (!--spec->count) {
2645                diff_free_filespec_data(spec);
2646                free(spec);
2647        }
2648}
2649
2650void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
2651                   int sha1_valid, unsigned short mode)
2652{
2653        if (mode) {
2654                spec->mode = canon_mode(mode);
2655                hashcpy(spec->sha1, sha1);
2656                spec->sha1_valid = sha1_valid;
2657        }
2658}
2659
2660/*
2661 * Given a name and sha1 pair, if the index tells us the file in
2662 * the work tree has that object contents, return true, so that
2663 * prepare_temp_file() does not have to inflate and extract.
2664 */
2665static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
2666{
2667        const struct cache_entry *ce;
2668        struct stat st;
2669        int pos, len;
2670
2671        /*
2672         * We do not read the cache ourselves here, because the
2673         * benchmark with my previous version that always reads cache
2674         * shows that it makes things worse for diff-tree comparing
2675         * two linux-2.6 kernel trees in an already checked out work
2676         * tree.  This is because most diff-tree comparisons deal with
2677         * only a small number of files, while reading the cache is
2678         * expensive for a large project, and its cost outweighs the
2679         * savings we get by not inflating the object to a temporary
2680         * file.  Practically, this code only helps when we are used
2681         * by diff-cache --cached, which does read the cache before
2682         * calling us.
2683         */
2684        if (!active_cache)
2685                return 0;
2686
2687        /* We want to avoid the working directory if our caller
2688         * doesn't need the data in a normal file, this system
2689         * is rather slow with its stat/open/mmap/close syscalls,
2690         * and the object is contained in a pack file.  The pack
2691         * is probably already open and will be faster to obtain
2692         * the data through than the working directory.  Loose
2693         * objects however would tend to be slower as they need
2694         * to be individually opened and inflated.
2695         */
2696        if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
2697                return 0;
2698
2699        len = strlen(name);
2700        pos = cache_name_pos(name, len);
2701        if (pos < 0)
2702                return 0;
2703        ce = active_cache[pos];
2704
2705        /*
2706         * This is not the sha1 we are looking for, or
2707         * unreusable because it is not a regular file.
2708         */
2709        if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
2710                return 0;
2711
2712        /*
2713         * If ce is marked as "assume unchanged", there is no
2714         * guarantee that work tree matches what we are looking for.
2715         */
2716        if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2717                return 0;
2718
2719        /*
2720         * If ce matches the file in the work tree, we can reuse it.
2721         */
2722        if (ce_uptodate(ce) ||
2723            (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2724                return 1;
2725
2726        return 0;
2727}
2728
2729static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2730{
2731        struct strbuf buf = STRBUF_INIT;
2732        char *dirty = "";
2733
2734        /* Are we looking at the work tree? */
2735        if (s->dirty_submodule)
2736                dirty = "-dirty";
2737
2738        strbuf_addf(&buf, "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2739        s->size = buf.len;
2740        if (size_only) {
2741                s->data = NULL;
2742                strbuf_release(&buf);
2743        } else {
2744                s->data = strbuf_detach(&buf, NULL);
2745                s->should_free = 1;
2746        }
2747        return 0;
2748}
2749
2750/*
2751 * While doing rename detection and pickaxe operation, we may need to
2752 * grab the data for the blob (or file) for our own in-core comparison.
2753 * diff_filespec has data and size fields for this purpose.
2754 */
2755int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
2756{
2757        int size_only = flags & CHECK_SIZE_ONLY;
2758        int err = 0;
2759        /*
2760         * demote FAIL to WARN to allow inspecting the situation
2761         * instead of refusing.
2762         */
2763        enum safe_crlf crlf_warn = (safe_crlf == SAFE_CRLF_FAIL
2764                                    ? SAFE_CRLF_WARN
2765                                    : safe_crlf);
2766
2767        if (!DIFF_FILE_VALID(s))
2768                die("internal error: asking to populate invalid file.");
2769        if (S_ISDIR(s->mode))
2770                return -1;
2771
2772        if (s->data)
2773                return 0;
2774
2775        if (size_only && 0 < s->size)
2776                return 0;
2777
2778        if (S_ISGITLINK(s->mode))
2779                return diff_populate_gitlink(s, size_only);
2780
2781        if (!s->sha1_valid ||
2782            reuse_worktree_file(s->path, s->sha1, 0)) {
2783                struct strbuf buf = STRBUF_INIT;
2784                struct stat st;
2785                int fd;
2786
2787                if (lstat(s->path, &st) < 0) {
2788                        if (errno == ENOENT) {
2789                        err_empty:
2790                                err = -1;
2791                        empty:
2792                                s->data = (char *)"";
2793                                s->size = 0;
2794                                return err;
2795                        }
2796                }
2797                s->size = xsize_t(st.st_size);
2798                if (!s->size)
2799                        goto empty;
2800                if (S_ISLNK(st.st_mode)) {
2801                        struct strbuf sb = STRBUF_INIT;
2802
2803                        if (strbuf_readlink(&sb, s->path, s->size))
2804                                goto err_empty;
2805                        s->size = sb.len;
2806                        s->data = strbuf_detach(&sb, NULL);
2807                        s->should_free = 1;
2808                        return 0;
2809                }
2810                if (size_only)
2811                        return 0;
2812                if ((flags & CHECK_BINARY) &&
2813                    s->size > big_file_threshold && s->is_binary == -1) {
2814                        s->is_binary = 1;
2815                        return 0;
2816                }
2817                fd = open(s->path, O_RDONLY);
2818                if (fd < 0)
2819                        goto err_empty;
2820                s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2821                close(fd);
2822                s->should_munmap = 1;
2823
2824                /*
2825                 * Convert from working tree format to canonical git format
2826                 */
2827                if (convert_to_git(s->path, s->data, s->size, &buf, crlf_warn)) {
2828                        size_t size = 0;
2829                        munmap(s->data, s->size);
2830                        s->should_munmap = 0;
2831                        s->data = strbuf_detach(&buf, &size);
2832                        s->size = size;
2833                        s->should_free = 1;
2834                }
2835        }
2836        else {
2837                enum object_type type;
2838                if (size_only || (flags & CHECK_BINARY)) {
2839                        type = sha1_object_info(s->sha1, &s->size);
2840                        if (type < 0)
2841                                die("unable to read %s", sha1_to_hex(s->sha1));
2842                        if (size_only)
2843                                return 0;
2844                        if (s->size > big_file_threshold && s->is_binary == -1) {
2845                                s->is_binary = 1;
2846                                return 0;
2847                        }
2848                }
2849                s->data = read_sha1_file(s->sha1, &type, &s->size);
2850                if (!s->data)
2851                        die("unable to read %s", sha1_to_hex(s->sha1));
2852                s->should_free = 1;
2853        }
2854        return 0;
2855}
2856
2857void diff_free_filespec_blob(struct diff_filespec *s)
2858{
2859        if (s->should_free)
2860                free(s->data);
2861        else if (s->should_munmap)
2862                munmap(s->data, s->size);
2863
2864        if (s->should_free || s->should_munmap) {
2865                s->should_free = s->should_munmap = 0;
2866                s->data = NULL;
2867        }
2868}
2869
2870void diff_free_filespec_data(struct diff_filespec *s)
2871{
2872        diff_free_filespec_blob(s);
2873        free(s->cnt_data);
2874        s->cnt_data = NULL;
2875}
2876
2877static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2878                           void *blob,
2879                           unsigned long size,
2880                           const unsigned char *sha1,
2881                           int mode)
2882{
2883        int fd;
2884        struct strbuf buf = STRBUF_INIT;
2885        struct strbuf template = STRBUF_INIT;
2886        char *path_dup = xstrdup(path);
2887        const char *base = basename(path_dup);
2888
2889        /* Generate "XXXXXX_basename.ext" */
2890        strbuf_addstr(&template, "XXXXXX_");
2891        strbuf_addstr(&template, base);
2892
2893        fd = mks_tempfile_ts(&temp->tempfile, template.buf, strlen(base) + 1);
2894        if (fd < 0)
2895                die_errno("unable to create temp-file");
2896        if (convert_to_working_tree(path,
2897                        (const char *)blob, (size_t)size, &buf)) {
2898                blob = buf.buf;
2899                size = buf.len;
2900        }
2901        if (write_in_full(fd, blob, size) != size)
2902                die_errno("unable to write temp-file");
2903        close_tempfile(&temp->tempfile);
2904        temp->name = get_tempfile_path(&temp->tempfile);
2905        sha1_to_hex_r(temp->hex, sha1);
2906        xsnprintf(temp->mode, sizeof(temp->mode), "%06o", mode);
2907        strbuf_release(&buf);
2908        strbuf_release(&template);
2909        free(path_dup);
2910}
2911
2912static struct diff_tempfile *prepare_temp_file(const char *name,
2913                struct diff_filespec *one)
2914{
2915        struct diff_tempfile *temp = claim_diff_tempfile();
2916
2917        if (!DIFF_FILE_VALID(one)) {
2918        not_a_valid_file:
2919                /* A '-' entry produces this for file-2, and
2920                 * a '+' entry produces this for file-1.
2921                 */
2922                temp->name = "/dev/null";
2923                xsnprintf(temp->hex, sizeof(temp->hex), ".");
2924                xsnprintf(temp->mode, sizeof(temp->mode), ".");
2925                return temp;
2926        }
2927
2928        if (!S_ISGITLINK(one->mode) &&
2929            (!one->sha1_valid ||
2930             reuse_worktree_file(name, one->sha1, 1))) {
2931                struct stat st;
2932                if (lstat(name, &st) < 0) {
2933                        if (errno == ENOENT)
2934                                goto not_a_valid_file;
2935                        die_errno("stat(%s)", name);
2936                }
2937                if (S_ISLNK(st.st_mode)) {
2938                        struct strbuf sb = STRBUF_INIT;
2939                        if (strbuf_readlink(&sb, name, st.st_size) < 0)
2940                                die_errno("readlink(%s)", name);
2941                        prep_temp_blob(name, temp, sb.buf, sb.len,
2942                                       (one->sha1_valid ?
2943                                        one->sha1 : null_sha1),
2944                                       (one->sha1_valid ?
2945                                        one->mode : S_IFLNK));
2946                        strbuf_release(&sb);
2947                }
2948                else {
2949                        /* we can borrow from the file in the work tree */
2950                        temp->name = name;
2951                        if (!one->sha1_valid)
2952                                sha1_to_hex_r(temp->hex, null_sha1);
2953                        else
2954                                sha1_to_hex_r(temp->hex, one->sha1);
2955                        /* Even though we may sometimes borrow the
2956                         * contents from the work tree, we always want
2957                         * one->mode.  mode is trustworthy even when
2958                         * !(one->sha1_valid), as long as
2959                         * DIFF_FILE_VALID(one).
2960                         */
2961                        xsnprintf(temp->mode, sizeof(temp->mode), "%06o", one->mode);
2962                }
2963                return temp;
2964        }
2965        else {
2966                if (diff_populate_filespec(one, 0))
2967                        die("cannot read data blob for %s", one->path);
2968                prep_temp_blob(name, temp, one->data, one->size,
2969                               one->sha1, one->mode);
2970        }
2971        return temp;
2972}
2973
2974static void add_external_diff_name(struct argv_array *argv,
2975                                   const char *name,
2976                                   struct diff_filespec *df)
2977{
2978        struct diff_tempfile *temp = prepare_temp_file(name, df);
2979        argv_array_push(argv, temp->name);
2980        argv_array_push(argv, temp->hex);
2981        argv_array_push(argv, temp->mode);
2982}
2983
2984/* An external diff command takes:
2985 *
2986 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2987 *               infile2 infile2-sha1 infile2-mode [ rename-to ]
2988 *
2989 */
2990static void run_external_diff(const char *pgm,
2991                              const char *name,
2992                              const char *other,
2993                              struct diff_filespec *one,
2994                              struct diff_filespec *two,
2995                              const char *xfrm_msg,
2996                              int complete_rewrite,
2997                              struct diff_options *o)
2998{
2999        struct argv_array argv = ARGV_ARRAY_INIT;
3000        struct argv_array env = ARGV_ARRAY_INIT;
3001        struct diff_queue_struct *q = &diff_queued_diff;
3002
3003        argv_array_push(&argv, pgm);
3004        argv_array_push(&argv, name);
3005
3006        if (one && two) {
3007                add_external_diff_name(&argv, name, one);
3008                if (!other)
3009                        add_external_diff_name(&argv, name, two);
3010                else {
3011                        add_external_diff_name(&argv, other, two);
3012                        argv_array_push(&argv, other);
3013                        argv_array_push(&argv, xfrm_msg);
3014                }
3015        }
3016
3017        argv_array_pushf(&env, "GIT_DIFF_PATH_COUNTER=%d", ++o->diff_path_counter);
3018        argv_array_pushf(&env, "GIT_DIFF_PATH_TOTAL=%d", q->nr);
3019
3020        if (run_command_v_opt_cd_env(argv.argv, RUN_USING_SHELL, NULL, env.argv))
3021                die(_("external diff died, stopping at %s"), name);
3022
3023        remove_tempfile();
3024        argv_array_clear(&argv);
3025        argv_array_clear(&env);
3026}
3027
3028static int similarity_index(struct diff_filepair *p)
3029{
3030        return p->score * 100 / MAX_SCORE;
3031}
3032
3033static void fill_metainfo(struct strbuf *msg,
3034                          const char *name,
3035                          const char *other,
3036                          struct diff_filespec *one,
3037                          struct diff_filespec *two,
3038                          struct diff_options *o,
3039                          struct diff_filepair *p,
3040                          int *must_show_header,
3041                          int use_color)
3042{
3043        const char *set = diff_get_color(use_color, DIFF_METAINFO);
3044        const char *reset = diff_get_color(use_color, DIFF_RESET);
3045        const char *line_prefix = diff_line_prefix(o);
3046
3047        *must_show_header = 1;
3048        strbuf_init(msg, PATH_MAX * 2 + 300);
3049        switch (p->status) {
3050        case DIFF_STATUS_COPIED:
3051                strbuf_addf(msg, "%s%ssimilarity index %d%%",
3052                            line_prefix, set, similarity_index(p));
3053                strbuf_addf(msg, "%s\n%s%scopy from ",
3054                            reset,  line_prefix, set);
3055                quote_c_style(name, msg, NULL, 0);
3056                strbuf_addf(msg, "%s\n%s%scopy to ", reset, line_prefix, set);
3057                quote_c_style(other, msg, NULL, 0);
3058                strbuf_addf(msg, "%s\n", reset);
3059                break;
3060        case DIFF_STATUS_RENAMED:
3061                strbuf_addf(msg, "%s%ssimilarity index %d%%",
3062                            line_prefix, set, similarity_index(p));
3063                strbuf_addf(msg, "%s\n%s%srename from ",
3064                            reset, line_prefix, set);
3065                quote_c_style(name, msg, NULL, 0);
3066                strbuf_addf(msg, "%s\n%s%srename to ",
3067                            reset, line_prefix, set);
3068                quote_c_style(other, msg, NULL, 0);
3069                strbuf_addf(msg, "%s\n", reset);
3070                break;
3071        case DIFF_STATUS_MODIFIED:
3072                if (p->score) {
3073                        strbuf_addf(msg, "%s%sdissimilarity index %d%%%s\n",
3074                                    line_prefix,
3075                                    set, similarity_index(p), reset);
3076                        break;
3077                }
3078                /* fallthru */
3079        default:
3080                *must_show_header = 0;
3081        }
3082        if (one && two && hashcmp(one->sha1, two->sha1)) {
3083                int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
3084
3085                if (DIFF_OPT_TST(o, BINARY)) {
3086                        mmfile_t mf;
3087                        if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
3088                            (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
3089                                abbrev = 40;
3090                }
3091                strbuf_addf(msg, "%s%sindex %s..", line_prefix, set,
3092                            find_unique_abbrev(one->sha1, abbrev));
3093                strbuf_addstr(msg, find_unique_abbrev(two->sha1, abbrev));
3094                if (one->mode == two->mode)
3095                        strbuf_addf(msg, " %06o", one->mode);
3096                strbuf_addf(msg, "%s\n", reset);
3097        }
3098}
3099
3100static void run_diff_cmd(const char *pgm,
3101                         const char *name,
3102                         const char *other,
3103                         const char *attr_path,
3104                         struct diff_filespec *one,
3105                         struct diff_filespec *two,
3106                         struct strbuf *msg,
3107                         struct diff_options *o,
3108                         struct diff_filepair *p)
3109{
3110        const char *xfrm_msg = NULL;
3111        int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
3112        int must_show_header = 0;
3113
3114
3115        if (DIFF_OPT_TST(o, ALLOW_EXTERNAL)) {
3116                struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
3117                if (drv && drv->external)
3118                        pgm = drv->external;
3119        }
3120
3121        if (msg) {
3122                /*
3123                 * don't use colors when the header is intended for an
3124                 * external diff driver
3125                 */
3126                fill_metainfo(msg, name, other, one, two, o, p,
3127                              &must_show_header,
3128                              want_color(o->use_color) && !pgm);
3129                xfrm_msg = msg->len ? msg->buf : NULL;
3130        }
3131
3132        if (pgm) {
3133                run_external_diff(pgm, name, other, one, two, xfrm_msg,
3134                                  complete_rewrite, o);
3135                return;
3136        }
3137        if (one && two)
3138                builtin_diff(name, other ? other : name,
3139                             one, two, xfrm_msg, must_show_header,
3140                             o, complete_rewrite);
3141        else
3142                fprintf(o->file, "* Unmerged path %s\n", name);
3143}
3144
3145static void diff_fill_sha1_info(struct diff_filespec *one)
3146{
3147        if (DIFF_FILE_VALID(one)) {
3148                if (!one->sha1_valid) {
3149                        struct stat st;
3150                        if (one->is_stdin) {
3151                                hashcpy(one->sha1, null_sha1);
3152                                return;
3153                        }
3154                        if (lstat(one->path, &st) < 0)
3155                                die_errno("stat '%s'", one->path);
3156                        if (index_path(one->sha1, one->path, &st, 0))
3157                                die("cannot hash %s", one->path);
3158                }
3159        }
3160        else
3161                hashclr(one->sha1);
3162}
3163
3164static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
3165{
3166        /* Strip the prefix but do not molest /dev/null and absolute paths */
3167        if (*namep && **namep != '/') {
3168                *namep += prefix_length;
3169                if (**namep == '/')
3170                        ++*namep;
3171        }
3172        if (*otherp && **otherp != '/') {
3173                *otherp += prefix_length;
3174                if (**otherp == '/')
3175                        ++*otherp;
3176        }
3177}
3178
3179static void run_diff(struct diff_filepair *p, struct diff_options *o)
3180{
3181        const char *pgm = external_diff();
3182        struct strbuf msg;
3183        struct diff_filespec *one = p->one;
3184        struct diff_filespec *two = p->two;
3185        const char *name;
3186        const char *other;
3187        const char *attr_path;
3188
3189        name  = p->one->path;
3190        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3191        attr_path = name;
3192        if (o->prefix_length)
3193                strip_prefix(o->prefix_length, &name, &other);
3194
3195        if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
3196                pgm = NULL;
3197
3198        if (DIFF_PAIR_UNMERGED(p)) {
3199                run_diff_cmd(pgm, name, NULL, attr_path,
3200                             NULL, NULL, NULL, o, p);
3201                return;
3202        }
3203
3204        diff_fill_sha1_info(one);
3205        diff_fill_sha1_info(two);
3206
3207        if (!pgm &&
3208            DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
3209            (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
3210                /*
3211                 * a filepair that changes between file and symlink
3212                 * needs to be split into deletion and creation.
3213                 */
3214                struct diff_filespec *null = alloc_filespec(two->path);
3215                run_diff_cmd(NULL, name, other, attr_path,
3216                             one, null, &msg, o, p);
3217                free(null);
3218                strbuf_release(&msg);
3219
3220                null = alloc_filespec(one->path);
3221                run_diff_cmd(NULL, name, other, attr_path,
3222                             null, two, &msg, o, p);
3223                free(null);
3224        }
3225        else
3226                run_diff_cmd(pgm, name, other, attr_path,
3227                             one, two, &msg, o, p);
3228
3229        strbuf_release(&msg);
3230}
3231
3232static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
3233                         struct diffstat_t *diffstat)
3234{
3235        const char *name;
3236        const char *other;
3237
3238        if (DIFF_PAIR_UNMERGED(p)) {
3239                /* unmerged */
3240                builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, p);
3241                return;
3242        }
3243
3244        name = p->one->path;
3245        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3246
3247        if (o->prefix_length)
3248                strip_prefix(o->prefix_length, &name, &other);
3249
3250        diff_fill_sha1_info(p->one);
3251        diff_fill_sha1_info(p->two);
3252
3253        builtin_diffstat(name, other, p->one, p->two, diffstat, o, p);
3254}
3255
3256static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
3257{
3258        const char *name;
3259        const char *other;
3260        const char *attr_path;
3261
3262        if (DIFF_PAIR_UNMERGED(p)) {
3263                /* unmerged */
3264                return;
3265        }
3266
3267        name = p->one->path;
3268        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
3269        attr_path = other ? other : name;
3270
3271        if (o->prefix_length)
3272                strip_prefix(o->prefix_length, &name, &other);
3273
3274        diff_fill_sha1_info(p->one);
3275        diff_fill_sha1_info(p->two);
3276
3277        builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
3278}
3279
3280void diff_setup(struct diff_options *options)
3281{
3282        memcpy(options, &default_diff_options, sizeof(*options));
3283
3284        options->file = stdout;
3285
3286        options->line_termination = '\n';
3287        options->break_opt = -1;
3288        options->rename_limit = -1;
3289        options->dirstat_permille = diff_dirstat_permille_default;
3290        options->context = diff_context_default;
3291        options->ws_error_highlight = WSEH_NEW;
3292        DIFF_OPT_SET(options, RENAME_EMPTY);
3293
3294        /* pathchange left =NULL by default */
3295        options->change = diff_change;
3296        options->add_remove = diff_addremove;
3297        options->use_color = diff_use_color_default;
3298        options->detect_rename = diff_detect_rename_default;
3299        options->xdl_opts |= diff_algorithm;
3300        if (diff_indent_heuristic)
3301                DIFF_XDL_SET(options, INDENT_HEURISTIC);
3302        else if (diff_compaction_heuristic)
3303                DIFF_XDL_SET(options, COMPACTION_HEURISTIC);
3304
3305        options->orderfile = diff_order_file_cfg;
3306
3307        if (diff_no_prefix) {
3308                options->a_prefix = options->b_prefix = "";
3309        } else if (!diff_mnemonic_prefix) {
3310                options->a_prefix = "a/";
3311                options->b_prefix = "b/";
3312        }
3313}
3314
3315void diff_setup_done(struct diff_options *options)
3316{
3317        int count = 0;
3318
3319        if (options->set_default)
3320                options->set_default(options);
3321
3322        if (options->output_format & DIFF_FORMAT_NAME)
3323                count++;
3324        if (options->output_format & DIFF_FORMAT_NAME_STATUS)
3325                count++;
3326        if (options->output_format & DIFF_FORMAT_CHECKDIFF)
3327                count++;
3328        if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
3329                count++;
3330        if (count > 1)
3331                die("--name-only, --name-status, --check and -s are mutually exclusive");
3332
3333        /*
3334         * Most of the time we can say "there are changes"
3335         * only by checking if there are changed paths, but
3336         * --ignore-whitespace* options force us to look
3337         * inside contents.
3338         */
3339
3340        if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
3341            DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
3342            DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
3343                DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
3344        else
3345                DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
3346
3347        if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
3348                options->detect_rename = DIFF_DETECT_COPY;
3349
3350        if (!DIFF_OPT_TST(options, RELATIVE_NAME))
3351                options->prefix = NULL;
3352        if (options->prefix)
3353                options->prefix_length = strlen(options->prefix);
3354        else
3355                options->prefix_length = 0;
3356
3357        if (options->output_format & (DIFF_FORMAT_NAME |
3358                                      DIFF_FORMAT_NAME_STATUS |
3359                                      DIFF_FORMAT_CHECKDIFF |
3360                                      DIFF_FORMAT_NO_OUTPUT))
3361                options->output_format &= ~(DIFF_FORMAT_RAW |
3362                                            DIFF_FORMAT_NUMSTAT |
3363                                            DIFF_FORMAT_DIFFSTAT |
3364                                            DIFF_FORMAT_SHORTSTAT |
3365                                            DIFF_FORMAT_DIRSTAT |
3366                                            DIFF_FORMAT_SUMMARY |
3367                                            DIFF_FORMAT_PATCH);
3368
3369        /*
3370         * These cases always need recursive; we do not drop caller-supplied
3371         * recursive bits for other formats here.
3372         */
3373        if (options->output_format & (DIFF_FORMAT_PATCH |
3374                                      DIFF_FORMAT_NUMSTAT |
3375                                      DIFF_FORMAT_DIFFSTAT |
3376                                      DIFF_FORMAT_SHORTSTAT |
3377                                      DIFF_FORMAT_DIRSTAT |
3378                                      DIFF_FORMAT_SUMMARY |
3379                                      DIFF_FORMAT_CHECKDIFF))
3380                DIFF_OPT_SET(options, RECURSIVE);
3381        /*
3382         * Also pickaxe would not work very well if you do not say recursive
3383         */
3384        if (options->pickaxe)
3385                DIFF_OPT_SET(options, RECURSIVE);
3386        /*
3387         * When patches are generated, submodules diffed against the work tree
3388         * must be checked for dirtiness too so it can be shown in the output
3389         */
3390        if (options->output_format & DIFF_FORMAT_PATCH)
3391                DIFF_OPT_SET(options, DIRTY_SUBMODULES);
3392
3393        if (options->detect_rename && options->rename_limit < 0)
3394                options->rename_limit = diff_rename_limit_default;
3395        if (options->setup & DIFF_SETUP_USE_CACHE) {
3396                if (!active_cache)
3397                        /* read-cache does not die even when it fails
3398                         * so it is safe for us to do this here.  Also
3399                         * it does not smudge active_cache or active_nr
3400                         * when it fails, so we do not have to worry about
3401                         * cleaning it up ourselves either.
3402                         */
3403                        read_cache();
3404        }
3405        if (options->abbrev <= 0 || 40 < options->abbrev)
3406                options->abbrev = 40; /* full */
3407
3408        /*
3409         * It does not make sense to show the first hit we happened
3410         * to have found.  It does not make sense not to return with
3411         * exit code in such a case either.
3412         */
3413        if (DIFF_OPT_TST(options, QUICK)) {
3414                options->output_format = DIFF_FORMAT_NO_OUTPUT;
3415                DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3416        }
3417
3418        options->diff_path_counter = 0;
3419
3420        if (DIFF_OPT_TST(options, FOLLOW_RENAMES) && options->pathspec.nr != 1)
3421                die(_("--follow requires exactly one pathspec"));
3422}
3423
3424static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
3425{
3426        char c, *eq;
3427        int len;
3428
3429        if (*arg != '-')
3430                return 0;
3431        c = *++arg;
3432        if (!c)
3433                return 0;
3434        if (c == arg_short) {
3435                c = *++arg;
3436                if (!c)
3437                        return 1;
3438                if (val && isdigit(c)) {
3439                        char *end;
3440                        int n = strtoul(arg, &end, 10);
3441                        if (*end)
3442                                return 0;
3443                        *val = n;
3444                        return 1;
3445                }
3446                return 0;
3447        }
3448        if (c != '-')
3449                return 0;
3450        arg++;
3451        eq = strchrnul(arg, '=');
3452        len = eq - arg;
3453        if (!len || strncmp(arg, arg_long, len))
3454                return 0;
3455        if (*eq) {
3456                int n;
3457                char *end;
3458                if (!isdigit(*++eq))
3459                        return 0;
3460                n = strtoul(eq, &end, 10);
3461                if (*end)
3462                        return 0;
3463                *val = n;
3464        }
3465        return 1;
3466}
3467
3468static int diff_scoreopt_parse(const char *opt);
3469
3470static inline int short_opt(char opt, const char **argv,
3471                            const char **optarg)
3472{
3473        const char *arg = argv[0];
3474        if (arg[0] != '-' || arg[1] != opt)
3475                return 0;
3476        if (arg[2] != '\0') {
3477                *optarg = arg + 2;
3478                return 1;
3479        }
3480        if (!argv[1])
3481                die("Option '%c' requires a value", opt);
3482        *optarg = argv[1];
3483        return 2;
3484}
3485
3486int parse_long_opt(const char *opt, const char **argv,
3487                   const char **optarg)
3488{
3489        const char *arg = argv[0];
3490        if (!skip_prefix(arg, "--", &arg))
3491                return 0;
3492        if (!skip_prefix(arg, opt, &arg))
3493                return 0;
3494        if (*arg == '=') { /* stuck form: --option=value */
3495                *optarg = arg + 1;
3496                return 1;
3497        }
3498        if (*arg != '\0')
3499                return 0;
3500        /* separate form: --option value */
3501        if (!argv[1])
3502                die("Option '--%s' requires a value", opt);
3503        *optarg = argv[1];
3504        return 2;
3505}
3506
3507static int stat_opt(struct diff_options *options, const char **av)
3508{
3509        const char *arg = av[0];
3510        char *end;
3511        int width = options->stat_width;
3512        int name_width = options->stat_name_width;
3513        int graph_width = options->stat_graph_width;
3514        int count = options->stat_count;
3515        int argcount = 1;
3516
3517        if (!skip_prefix(arg, "--stat", &arg))
3518                die("BUG: stat option does not begin with --stat: %s", arg);
3519        end = (char *)arg;
3520
3521        switch (*arg) {
3522        case '-':
3523                if (skip_prefix(arg, "-width", &arg)) {
3524                        if (*arg == '=')
3525                                width = strtoul(arg + 1, &end, 10);
3526                        else if (!*arg && !av[1])
3527                                die("Option '--stat-width' requires a value");
3528                        else if (!*arg) {
3529                                width = strtoul(av[1], &end, 10);
3530                                argcount = 2;
3531                        }
3532                } else if (skip_prefix(arg, "-name-width", &arg)) {
3533                        if (*arg == '=')
3534                                name_width = strtoul(arg + 1, &end, 10);
3535                        else if (!*arg && !av[1])
3536                                die("Option '--stat-name-width' requires a value");
3537                        else if (!*arg) {
3538                                name_width = strtoul(av[1], &end, 10);
3539                                argcount = 2;
3540                        }
3541                } else if (skip_prefix(arg, "-graph-width", &arg)) {
3542                        if (*arg == '=')
3543                                graph_width = strtoul(arg + 1, &end, 10);
3544                        else if (!*arg && !av[1])
3545                                die("Option '--stat-graph-width' requires a value");
3546                        else if (!*arg) {
3547                                graph_width = strtoul(av[1], &end, 10);
3548                                argcount = 2;
3549                        }
3550                } else if (skip_prefix(arg, "-count", &arg)) {
3551                        if (*arg == '=')
3552                                count = strtoul(arg + 1, &end, 10);
3553                        else if (!*arg && !av[1])
3554                                die("Option '--stat-count' requires a value");
3555                        else if (!*arg) {
3556                                count = strtoul(av[1], &end, 10);
3557                                argcount = 2;
3558                        }
3559                }
3560                break;
3561        case '=':
3562                width = strtoul(arg+1, &end, 10);
3563                if (*end == ',')
3564                        name_width = strtoul(end+1, &end, 10);
3565                if (*end == ',')
3566                        count = strtoul(end+1, &end, 10);
3567        }
3568
3569        /* Important! This checks all the error cases! */
3570        if (*end)
3571                return 0;
3572        options->output_format |= DIFF_FORMAT_DIFFSTAT;
3573        options->stat_name_width = name_width;
3574        options->stat_graph_width = graph_width;
3575        options->stat_width = width;
3576        options->stat_count = count;
3577        return argcount;
3578}
3579
3580static int parse_dirstat_opt(struct diff_options *options, const char *params)
3581{
3582        struct strbuf errmsg = STRBUF_INIT;
3583        if (parse_dirstat_params(options, params, &errmsg))
3584                die(_("Failed to parse --dirstat/-X option parameter:\n%s"),
3585                    errmsg.buf);
3586        strbuf_release(&errmsg);
3587        /*
3588         * The caller knows a dirstat-related option is given from the command
3589         * line; allow it to say "return this_function();"
3590         */
3591        options->output_format |= DIFF_FORMAT_DIRSTAT;
3592        return 1;
3593}
3594
3595static int parse_submodule_opt(struct diff_options *options, const char *value)
3596{
3597        if (parse_submodule_params(options, value))
3598                die(_("Failed to parse --submodule option parameter: '%s'"),
3599                        value);
3600        return 1;
3601}
3602
3603static const char diff_status_letters[] = {
3604        DIFF_STATUS_ADDED,
3605        DIFF_STATUS_COPIED,
3606        DIFF_STATUS_DELETED,
3607        DIFF_STATUS_MODIFIED,
3608        DIFF_STATUS_RENAMED,
3609        DIFF_STATUS_TYPE_CHANGED,
3610        DIFF_STATUS_UNKNOWN,
3611        DIFF_STATUS_UNMERGED,
3612        DIFF_STATUS_FILTER_AON,
3613        DIFF_STATUS_FILTER_BROKEN,
3614        '\0',
3615};
3616
3617static unsigned int filter_bit['Z' + 1];
3618
3619static void prepare_filter_bits(void)
3620{
3621        int i;
3622
3623        if (!filter_bit[DIFF_STATUS_ADDED]) {
3624                for (i = 0; diff_status_letters[i]; i++)
3625                        filter_bit[(int) diff_status_letters[i]] = (1 << i);
3626        }
3627}
3628
3629static unsigned filter_bit_tst(char status, const struct diff_options *opt)
3630{
3631        return opt->filter & filter_bit[(int) status];
3632}
3633
3634static int parse_diff_filter_opt(const char *optarg, struct diff_options *opt)
3635{
3636        int i, optch;
3637
3638        prepare_filter_bits();
3639
3640        /*
3641         * If there is a negation e.g. 'd' in the input, and we haven't
3642         * initialized the filter field with another --diff-filter, start
3643         * from full set of bits, except for AON.
3644         */
3645        if (!opt->filter) {
3646                for (i = 0; (optch = optarg[i]) != '\0'; i++) {
3647                        if (optch < 'a' || 'z' < optch)
3648                                continue;
3649                        opt->filter = (1 << (ARRAY_SIZE(diff_status_letters) - 1)) - 1;
3650                        opt->filter &= ~filter_bit[DIFF_STATUS_FILTER_AON];
3651                        break;
3652                }
3653        }
3654
3655        for (i = 0; (optch = optarg[i]) != '\0'; i++) {
3656                unsigned int bit;
3657                int negate;
3658
3659                if ('a' <= optch && optch <= 'z') {
3660                        negate = 1;
3661                        optch = toupper(optch);
3662                } else {
3663                        negate = 0;
3664                }
3665
3666                bit = (0 <= optch && optch <= 'Z') ? filter_bit[optch] : 0;
3667                if (!bit)
3668                        return optarg[i];
3669                if (negate)
3670                        opt->filter &= ~bit;
3671                else
3672                        opt->filter |= bit;
3673        }
3674        return 0;
3675}
3676
3677static void enable_patch_output(int *fmt) {
3678        *fmt &= ~DIFF_FORMAT_NO_OUTPUT;
3679        *fmt |= DIFF_FORMAT_PATCH;
3680}
3681
3682static int parse_one_token(const char **arg, const char *token)
3683{
3684        const char *rest;
3685        if (skip_prefix(*arg, token, &rest) && (!*rest || *rest == ',')) {
3686                *arg = rest;
3687                return 1;
3688        }
3689        return 0;
3690}
3691
3692static int parse_ws_error_highlight(struct diff_options *opt, const char *arg)
3693{
3694        const char *orig_arg = arg;
3695        unsigned val = 0;
3696        while (*arg) {
3697                if (parse_one_token(&arg, "none"))
3698                        val = 0;
3699                else if (parse_one_token(&arg, "default"))
3700                        val = WSEH_NEW;
3701                else if (parse_one_token(&arg, "all"))
3702                        val = WSEH_NEW | WSEH_OLD | WSEH_CONTEXT;
3703                else if (parse_one_token(&arg, "new"))
3704                        val |= WSEH_NEW;
3705                else if (parse_one_token(&arg, "old"))
3706                        val |= WSEH_OLD;
3707                else if (parse_one_token(&arg, "context"))
3708                        val |= WSEH_CONTEXT;
3709                else {
3710                        error("unknown value after ws-error-highlight=%.*s",
3711                              (int)(arg - orig_arg), orig_arg);
3712                        return 0;
3713                }
3714                if (*arg)
3715                        arg++;
3716        }
3717        opt->ws_error_highlight = val;
3718        return 1;
3719}
3720
3721int diff_opt_parse(struct diff_options *options,
3722                   const char **av, int ac, const char *prefix)
3723{
3724        const char *arg = av[0];
3725        const char *optarg;
3726        int argcount;
3727
3728        if (!prefix)
3729                prefix = "";
3730
3731        /* Output format options */
3732        if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch")
3733            || opt_arg(arg, 'U', "unified", &options->context))
3734                enable_patch_output(&options->output_format);
3735        else if (!strcmp(arg, "--raw"))
3736                options->output_format |= DIFF_FORMAT_RAW;
3737        else if (!strcmp(arg, "--patch-with-raw")) {
3738                enable_patch_output(&options->output_format);
3739                options->output_format |= DIFF_FORMAT_RAW;
3740        } else if (!strcmp(arg, "--numstat"))
3741                options->output_format |= DIFF_FORMAT_NUMSTAT;
3742        else if (!strcmp(arg, "--shortstat"))
3743                options->output_format |= DIFF_FORMAT_SHORTSTAT;
3744        else if (!strcmp(arg, "-X") || !strcmp(arg, "--dirstat"))
3745                return parse_dirstat_opt(options, "");
3746        else if (skip_prefix(arg, "-X", &arg))
3747                return parse_dirstat_opt(options, arg);
3748        else if (skip_prefix(arg, "--dirstat=", &arg))
3749                return parse_dirstat_opt(options, arg);
3750        else if (!strcmp(arg, "--cumulative"))
3751                return parse_dirstat_opt(options, "cumulative");
3752        else if (!strcmp(arg, "--dirstat-by-file"))
3753                return parse_dirstat_opt(options, "files");
3754        else if (skip_prefix(arg, "--dirstat-by-file=", &arg)) {
3755                parse_dirstat_opt(options, "files");
3756                return parse_dirstat_opt(options, arg);
3757        }
3758        else if (!strcmp(arg, "--check"))
3759                options->output_format |= DIFF_FORMAT_CHECKDIFF;
3760        else if (!strcmp(arg, "--summary"))
3761                options->output_format |= DIFF_FORMAT_SUMMARY;
3762        else if (!strcmp(arg, "--patch-with-stat")) {
3763                enable_patch_output(&options->output_format);
3764                options->output_format |= DIFF_FORMAT_DIFFSTAT;
3765        } else if (!strcmp(arg, "--name-only"))
3766                options->output_format |= DIFF_FORMAT_NAME;
3767        else if (!strcmp(arg, "--name-status"))
3768                options->output_format |= DIFF_FORMAT_NAME_STATUS;
3769        else if (!strcmp(arg, "-s") || !strcmp(arg, "--no-patch"))
3770                options->output_format |= DIFF_FORMAT_NO_OUTPUT;
3771        else if (starts_with(arg, "--stat"))
3772                /* --stat, --stat-width, --stat-name-width, or --stat-count */
3773                return stat_opt(options, av);
3774
3775        /* renames options */
3776        else if (starts_with(arg, "-B") || starts_with(arg, "--break-rewrites=") ||
3777                 !strcmp(arg, "--break-rewrites")) {
3778                if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
3779                        return error("invalid argument to -B: %s", arg+2);
3780        }
3781        else if (starts_with(arg, "-M") || starts_with(arg, "--find-renames=") ||
3782                 !strcmp(arg, "--find-renames")) {
3783                if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3784                        return error("invalid argument to -M: %s", arg+2);
3785                options->detect_rename = DIFF_DETECT_RENAME;
3786        }
3787        else if (!strcmp(arg, "-D") || !strcmp(arg, "--irreversible-delete")) {
3788                options->irreversible_delete = 1;
3789        }
3790        else if (starts_with(arg, "-C") || starts_with(arg, "--find-copies=") ||
3791                 !strcmp(arg, "--find-copies")) {
3792                if (options->detect_rename == DIFF_DETECT_COPY)
3793                        DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3794                if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
3795                        return error("invalid argument to -C: %s", arg+2);
3796                options->detect_rename = DIFF_DETECT_COPY;
3797        }
3798        else if (!strcmp(arg, "--no-renames"))
3799                options->detect_rename = 0;
3800        else if (!strcmp(arg, "--rename-empty"))
3801                DIFF_OPT_SET(options, RENAME_EMPTY);
3802        else if (!strcmp(arg, "--no-rename-empty"))
3803                DIFF_OPT_CLR(options, RENAME_EMPTY);
3804        else if (!strcmp(arg, "--relative"))
3805                DIFF_OPT_SET(options, RELATIVE_NAME);
3806        else if (skip_prefix(arg, "--relative=", &arg)) {
3807                DIFF_OPT_SET(options, RELATIVE_NAME);
3808                options->prefix = arg;
3809        }
3810
3811        /* xdiff options */
3812        else if (!strcmp(arg, "--minimal"))
3813                DIFF_XDL_SET(options, NEED_MINIMAL);
3814        else if (!strcmp(arg, "--no-minimal"))
3815                DIFF_XDL_CLR(options, NEED_MINIMAL);
3816        else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
3817                DIFF_XDL_SET(options, IGNORE_WHITESPACE);
3818        else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
3819                DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
3820        else if (!strcmp(arg, "--ignore-space-at-eol"))
3821                DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
3822        else if (!strcmp(arg, "--ignore-blank-lines"))
3823                DIFF_XDL_SET(options, IGNORE_BLANK_LINES);
3824        else if (!strcmp(arg, "--indent-heuristic")) {
3825                DIFF_XDL_SET(options, INDENT_HEURISTIC);
3826                DIFF_XDL_CLR(options, COMPACTION_HEURISTIC);
3827        } else if (!strcmp(arg, "--no-indent-heuristic"))
3828                DIFF_XDL_CLR(options, INDENT_HEURISTIC);
3829        else if (!strcmp(arg, "--compaction-heuristic")) {
3830                DIFF_XDL_SET(options, COMPACTION_HEURISTIC);
3831                DIFF_XDL_CLR(options, INDENT_HEURISTIC);
3832        } else if (!strcmp(arg, "--no-compaction-heuristic"))
3833                DIFF_XDL_CLR(options, COMPACTION_HEURISTIC);
3834        else if (!strcmp(arg, "--patience"))
3835                options->xdl_opts = DIFF_WITH_ALG(options, PATIENCE_DIFF);
3836        else if (!strcmp(arg, "--histogram"))
3837                options->xdl_opts = DIFF_WITH_ALG(options, HISTOGRAM_DIFF);
3838        else if ((argcount = parse_long_opt("diff-algorithm", av, &optarg))) {
3839                long value = parse_algorithm_value(optarg);
3840                if (value < 0)
3841                        return error("option diff-algorithm accepts \"myers\", "
3842                                     "\"minimal\", \"patience\" and \"histogram\"");
3843                /* clear out previous settings */
3844                DIFF_XDL_CLR(options, NEED_MINIMAL);
3845                options->xdl_opts &= ~XDF_DIFF_ALGORITHM_MASK;
3846                options->xdl_opts |= value;
3847                return argcount;
3848        }
3849
3850        /* flags options */
3851        else if (!strcmp(arg, "--binary")) {
3852                enable_patch_output(&options->output_format);
3853                DIFF_OPT_SET(options, BINARY);
3854        }
3855        else if (!strcmp(arg, "--full-index"))
3856                DIFF_OPT_SET(options, FULL_INDEX);
3857        else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
3858                DIFF_OPT_SET(options, TEXT);
3859        else if (!strcmp(arg, "-R"))
3860                DIFF_OPT_SET(options, REVERSE_DIFF);
3861        else if (!strcmp(arg, "--find-copies-harder"))
3862                DIFF_OPT_SET(options, FIND_COPIES_HARDER);
3863        else if (!strcmp(arg, "--follow"))
3864                DIFF_OPT_SET(options, FOLLOW_RENAMES);
3865        else if (!strcmp(arg, "--no-follow")) {
3866                DIFF_OPT_CLR(options, FOLLOW_RENAMES);
3867                DIFF_OPT_CLR(options, DEFAULT_FOLLOW_RENAMES);
3868        } else if (!strcmp(arg, "--color"))
3869                options->use_color = 1;
3870        else if (skip_prefix(arg, "--color=", &arg)) {
3871                int value = git_config_colorbool(NULL, arg);
3872                if (value < 0)
3873                        return error("option `color' expects \"always\", \"auto\", or \"never\"");
3874                options->use_color = value;
3875        }
3876        else if (!strcmp(arg, "--no-color"))
3877                options->use_color = 0;
3878        else if (!strcmp(arg, "--color-words")) {
3879                options->use_color = 1;
3880                options->word_diff = DIFF_WORDS_COLOR;
3881        }
3882        else if (skip_prefix(arg, "--color-words=", &arg)) {
3883                options->use_color = 1;
3884                options->word_diff = DIFF_WORDS_COLOR;
3885                options->word_regex = arg;
3886        }
3887        else if (!strcmp(arg, "--word-diff")) {
3888                if (options->word_diff == DIFF_WORDS_NONE)
3889                        options->word_diff = DIFF_WORDS_PLAIN;
3890        }
3891        else if (skip_prefix(arg, "--word-diff=", &arg)) {
3892                if (!strcmp(arg, "plain"))
3893                        options->word_diff = DIFF_WORDS_PLAIN;
3894                else if (!strcmp(arg, "color")) {
3895                        options->use_color = 1;
3896                        options->word_diff = DIFF_WORDS_COLOR;
3897                }
3898                else if (!strcmp(arg, "porcelain"))
3899                        options->word_diff = DIFF_WORDS_PORCELAIN;
3900                else if (!strcmp(arg, "none"))
3901                        options->word_diff = DIFF_WORDS_NONE;
3902                else
3903                        die("bad --word-diff argument: %s", arg);
3904        }
3905        else if ((argcount = parse_long_opt("word-diff-regex", av, &optarg))) {
3906                if (options->word_diff == DIFF_WORDS_NONE)
3907                        options->word_diff = DIFF_WORDS_PLAIN;
3908                options->word_regex = optarg;
3909                return argcount;
3910        }
3911        else if (!strcmp(arg, "--exit-code"))
3912                DIFF_OPT_SET(options, EXIT_WITH_STATUS);
3913        else if (!strcmp(arg, "--quiet"))
3914                DIFF_OPT_SET(options, QUICK);
3915        else if (!strcmp(arg, "--ext-diff"))
3916                DIFF_OPT_SET(options, ALLOW_EXTERNAL);
3917        else if (!strcmp(arg, "--no-ext-diff"))
3918                DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
3919        else if (!strcmp(arg, "--textconv"))
3920                DIFF_OPT_SET(options, ALLOW_TEXTCONV);
3921        else if (!strcmp(arg, "--no-textconv"))
3922                DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
3923        else if (!strcmp(arg, "--ignore-submodules")) {
3924                DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3925                handle_ignore_submodules_arg(options, "all");
3926        } else if (skip_prefix(arg, "--ignore-submodules=", &arg)) {
3927                DIFF_OPT_SET(options, OVERRIDE_SUBMODULE_CONFIG);
3928                handle_ignore_submodules_arg(options, arg);
3929        } else if (!strcmp(arg, "--submodule"))
3930                DIFF_OPT_SET(options, SUBMODULE_LOG);
3931        else if (skip_prefix(arg, "--submodule=", &arg))
3932                return parse_submodule_opt(options, arg);
3933        else if (skip_prefix(arg, "--ws-error-highlight=", &arg))
3934                return parse_ws_error_highlight(options, arg);
3935
3936        /* misc options */
3937        else if (!strcmp(arg, "-z"))
3938                options->line_termination = 0;
3939        else if ((argcount = short_opt('l', av, &optarg))) {
3940                options->rename_limit = strtoul(optarg, NULL, 10);
3941                return argcount;
3942        }
3943        else if ((argcount = short_opt('S', av, &optarg))) {
3944                options->pickaxe = optarg;
3945                options->pickaxe_opts |= DIFF_PICKAXE_KIND_S;
3946                return argcount;
3947        } else if ((argcount = short_opt('G', av, &optarg))) {
3948                options->pickaxe = optarg;
3949                options->pickaxe_opts |= DIFF_PICKAXE_KIND_G;
3950                return argcount;
3951        }
3952        else if (!strcmp(arg, "--pickaxe-all"))
3953                options->pickaxe_opts |= DIFF_PICKAXE_ALL;
3954        else if (!strcmp(arg, "--pickaxe-regex"))
3955                options->pickaxe_opts |= DIFF_PICKAXE_REGEX;
3956        else if ((argcount = short_opt('O', av, &optarg))) {
3957                const char *path = prefix_filename(prefix, strlen(prefix), optarg);
3958                options->orderfile = xstrdup(path);
3959                return argcount;
3960        }
3961        else if ((argcount = parse_long_opt("diff-filter", av, &optarg))) {
3962                int offending = parse_diff_filter_opt(optarg, options);
3963                if (offending)
3964                        die("unknown change class '%c' in --diff-filter=%s",
3965                            offending, optarg);
3966                return argcount;
3967        }
3968        else if (!strcmp(arg, "--abbrev"))
3969                options->abbrev = DEFAULT_ABBREV;
3970        else if (skip_prefix(arg, "--abbrev=", &arg)) {
3971                options->abbrev = strtoul(arg, NULL, 10);
3972                if (options->abbrev < MINIMUM_ABBREV)
3973                        options->abbrev = MINIMUM_ABBREV;
3974                else if (40 < options->abbrev)
3975                        options->abbrev = 40;
3976        }
3977        else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
3978                options->a_prefix = optarg;
3979                return argcount;
3980        }
3981        else if ((argcount = parse_long_opt("dst-prefix", av, &optarg))) {
3982                options->b_prefix = optarg;
3983                return argcount;
3984        }
3985        else if (!strcmp(arg, "--no-prefix"))
3986                options->a_prefix = options->b_prefix = "";
3987        else if (opt_arg(arg, '\0', "inter-hunk-context",
3988                         &options->interhunkcontext))
3989                ;
3990        else if (!strcmp(arg, "-W"))
3991                DIFF_OPT_SET(options, FUNCCONTEXT);
3992        else if (!strcmp(arg, "--function-context"))
3993                DIFF_OPT_SET(options, FUNCCONTEXT);
3994        else if (!strcmp(arg, "--no-function-context"))
3995                DIFF_OPT_CLR(options, FUNCCONTEXT);
3996        else if ((argcount = parse_long_opt("output", av, &optarg))) {
3997                const char *path = prefix_filename(prefix, strlen(prefix), optarg);
3998                options->file = fopen(path, "w");
3999                if (!options->file)
4000                        die_errno("Could not open '%s'", path);
4001                options->close_file = 1;
4002                return argcount;
4003        } else
4004                return 0;
4005        return 1;
4006}
4007
4008int parse_rename_score(const char **cp_p)
4009{
4010        unsigned long num, scale;
4011        int ch, dot;
4012        const char *cp = *cp_p;
4013
4014        num = 0;
4015        scale = 1;
4016        dot = 0;
4017        for (;;) {
4018                ch = *cp;
4019                if ( !dot && ch == '.' ) {
4020                        scale = 1;
4021                        dot = 1;
4022                } else if ( ch == '%' ) {
4023                        scale = dot ? scale*100 : 100;
4024                        cp++;   /* % is always at the end */
4025                        break;
4026                } else if ( ch >= '0' && ch <= '9' ) {
4027                        if ( scale < 100000 ) {
4028                                scale *= 10;
4029                                num = (num*10) + (ch-'0');
4030                        }
4031                } else {
4032                        break;
4033                }
4034                cp++;
4035        }
4036        *cp_p = cp;
4037
4038        /* user says num divided by scale and we say internally that
4039         * is MAX_SCORE * num / scale.
4040         */
4041        return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
4042}
4043
4044static int diff_scoreopt_parse(const char *opt)
4045{
4046        int opt1, opt2, cmd;
4047
4048        if (*opt++ != '-')
4049                return -1;
4050        cmd = *opt++;
4051        if (cmd == '-') {
4052                /* convert the long-form arguments into short-form versions */
4053                if (skip_prefix(opt, "break-rewrites", &opt)) {
4054                        if (*opt == 0 || *opt++ == '=')
4055                                cmd = 'B';
4056                } else if (skip_prefix(opt, "find-copies", &opt)) {
4057                        if (*opt == 0 || *opt++ == '=')
4058                                cmd = 'C';
4059                } else if (skip_prefix(opt, "find-renames", &opt)) {
4060                        if (*opt == 0 || *opt++ == '=')
4061                                cmd = 'M';
4062                }
4063        }
4064        if (cmd != 'M' && cmd != 'C' && cmd != 'B')
4065                return -1; /* that is not a -M, -C, or -B option */
4066
4067        opt1 = parse_rename_score(&opt);
4068        if (cmd != 'B')
4069                opt2 = 0;
4070        else {
4071                if (*opt == 0)
4072                        opt2 = 0;
4073                else if (*opt != '/')
4074                        return -1; /* we expect -B80/99 or -B80 */
4075                else {
4076                        opt++;
4077                        opt2 = parse_rename_score(&opt);
4078                }
4079        }
4080        if (*opt != 0)
4081                return -1;
4082        return opt1 | (opt2 << 16);
4083}
4084
4085struct diff_queue_struct diff_queued_diff;
4086
4087void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
4088{
4089        ALLOC_GROW(queue->queue, queue->nr + 1, queue->alloc);
4090        queue->queue[queue->nr++] = dp;
4091}
4092
4093struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
4094                                 struct diff_filespec *one,
4095                                 struct diff_filespec *two)
4096{
4097        struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
4098        dp->one = one;
4099        dp->two = two;
4100        if (queue)
4101                diff_q(queue, dp);
4102        return dp;
4103}
4104
4105void diff_free_filepair(struct diff_filepair *p)
4106{
4107        free_filespec(p->one);
4108        free_filespec(p->two);
4109        free(p);
4110}
4111
4112/* This is different from find_unique_abbrev() in that
4113 * it stuffs the result with dots for alignment.
4114 */
4115const char *diff_unique_abbrev(const unsigned char *sha1, int len)
4116{
4117        int abblen;
4118        const char *abbrev;
4119        if (len == 40)
4120                return sha1_to_hex(sha1);
4121
4122        abbrev = find_unique_abbrev(sha1, len);
4123        abblen = strlen(abbrev);
4124        if (abblen < 37) {
4125                static char hex[41];
4126                if (len < abblen && abblen <= len + 2)
4127                        xsnprintf(hex, sizeof(hex), "%s%.*s", abbrev, len+3-abblen, "..");
4128                else
4129                        xsnprintf(hex, sizeof(hex), "%s...", abbrev);
4130                return hex;
4131        }
4132        return sha1_to_hex(sha1);
4133}
4134
4135static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
4136{
4137        int line_termination = opt->line_termination;
4138        int inter_name_termination = line_termination ? '\t' : '\0';
4139
4140        fprintf(opt->file, "%s", diff_line_prefix(opt));
4141        if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
4142                fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
4143                        diff_unique_abbrev(p->one->sha1, opt->abbrev));
4144                fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
4145        }
4146        if (p->score) {
4147                fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
4148                        inter_name_termination);
4149        } else {
4150                fprintf(opt->file, "%c%c", p->status, inter_name_termination);
4151        }
4152
4153        if (p->status == DIFF_STATUS_COPIED ||
4154            p->status == DIFF_STATUS_RENAMED) {
4155                const char *name_a, *name_b;
4156                name_a = p->one->path;
4157                name_b = p->two->path;
4158                strip_prefix(opt->prefix_length, &name_a, &name_b);
4159                write_name_quoted(name_a, opt->file, inter_name_termination);
4160                write_name_quoted(name_b, opt->file, line_termination);
4161        } else {
4162                const char *name_a, *name_b;
4163                name_a = p->one->mode ? p->one->path : p->two->path;
4164                name_b = NULL;
4165                strip_prefix(opt->prefix_length, &name_a, &name_b);
4166                write_name_quoted(name_a, opt->file, line_termination);
4167        }
4168}
4169
4170int diff_unmodified_pair(struct diff_filepair *p)
4171{
4172        /* This function is written stricter than necessary to support
4173         * the currently implemented transformers, but the idea is to
4174         * let transformers to produce diff_filepairs any way they want,
4175         * and filter and clean them up here before producing the output.
4176         */
4177        struct diff_filespec *one = p->one, *two = p->two;
4178
4179        if (DIFF_PAIR_UNMERGED(p))
4180                return 0; /* unmerged is interesting */
4181
4182        /* deletion, addition, mode or type change
4183         * and rename are all interesting.
4184         */
4185        if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
4186            DIFF_PAIR_MODE_CHANGED(p) ||
4187            strcmp(one->path, two->path))
4188                return 0;
4189
4190        /* both are valid and point at the same path.  that is, we are
4191         * dealing with a change.
4192         */
4193        if (one->sha1_valid && two->sha1_valid &&
4194            !hashcmp(one->sha1, two->sha1) &&
4195            !one->dirty_submodule && !two->dirty_submodule)
4196                return 1; /* no change */
4197        if (!one->sha1_valid && !two->sha1_valid)
4198                return 1; /* both look at the same file on the filesystem. */
4199        return 0;
4200}
4201
4202static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
4203{
4204        if (diff_unmodified_pair(p))
4205                return;
4206
4207        if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4208            (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4209                return; /* no tree diffs in patch format */
4210
4211        run_diff(p, o);
4212}
4213
4214static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
4215                            struct diffstat_t *diffstat)
4216{
4217        if (diff_unmodified_pair(p))
4218                return;
4219
4220        if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4221            (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4222                return; /* no useful stat for tree diffs */
4223
4224        run_diffstat(p, o, diffstat);
4225}
4226
4227static void diff_flush_checkdiff(struct diff_filepair *p,
4228                struct diff_options *o)
4229{
4230        if (diff_unmodified_pair(p))
4231                return;
4232
4233        if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4234            (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4235                return; /* nothing to check in tree diffs */
4236
4237        run_checkdiff(p, o);
4238}
4239
4240int diff_queue_is_empty(void)
4241{
4242        struct diff_queue_struct *q = &diff_queued_diff;
4243        int i;
4244        for (i = 0; i < q->nr; i++)
4245                if (!diff_unmodified_pair(q->queue[i]))
4246                        return 0;
4247        return 1;
4248}
4249
4250#if DIFF_DEBUG
4251void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
4252{
4253        fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
4254                x, one ? one : "",
4255                s->path,
4256                DIFF_FILE_VALID(s) ? "valid" : "invalid",
4257                s->mode,
4258                s->sha1_valid ? sha1_to_hex(s->sha1) : "");
4259        fprintf(stderr, "queue[%d] %s size %lu\n",
4260                x, one ? one : "",
4261                s->size);
4262}
4263
4264void diff_debug_filepair(const struct diff_filepair *p, int i)
4265{
4266        diff_debug_filespec(p->one, i, "one");
4267        diff_debug_filespec(p->two, i, "two");
4268        fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
4269                p->score, p->status ? p->status : '?',
4270                p->one->rename_used, p->broken_pair);
4271}
4272
4273void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
4274{
4275        int i;
4276        if (msg)
4277                fprintf(stderr, "%s\n", msg);
4278        fprintf(stderr, "q->nr = %d\n", q->nr);
4279        for (i = 0; i < q->nr; i++) {
4280                struct diff_filepair *p = q->queue[i];
4281                diff_debug_filepair(p, i);
4282        }
4283}
4284#endif
4285
4286static void diff_resolve_rename_copy(void)
4287{
4288        int i;
4289        struct diff_filepair *p;
4290        struct diff_queue_struct *q = &diff_queued_diff;
4291
4292        diff_debug_queue("resolve-rename-copy", q);
4293
4294        for (i = 0; i < q->nr; i++) {
4295                p = q->queue[i];
4296                p->status = 0; /* undecided */
4297                if (DIFF_PAIR_UNMERGED(p))
4298                        p->status = DIFF_STATUS_UNMERGED;
4299                else if (!DIFF_FILE_VALID(p->one))
4300                        p->status = DIFF_STATUS_ADDED;
4301                else if (!DIFF_FILE_VALID(p->two))
4302                        p->status = DIFF_STATUS_DELETED;
4303                else if (DIFF_PAIR_TYPE_CHANGED(p))
4304                        p->status = DIFF_STATUS_TYPE_CHANGED;
4305
4306                /* from this point on, we are dealing with a pair
4307                 * whose both sides are valid and of the same type, i.e.
4308                 * either in-place edit or rename/copy edit.
4309                 */
4310                else if (DIFF_PAIR_RENAME(p)) {
4311                        /*
4312                         * A rename might have re-connected a broken
4313                         * pair up, causing the pathnames to be the
4314                         * same again. If so, that's not a rename at
4315                         * all, just a modification..
4316                         *
4317                         * Otherwise, see if this source was used for
4318                         * multiple renames, in which case we decrement
4319                         * the count, and call it a copy.
4320                         */
4321                        if (!strcmp(p->one->path, p->two->path))
4322                                p->status = DIFF_STATUS_MODIFIED;
4323                        else if (--p->one->rename_used > 0)
4324                                p->status = DIFF_STATUS_COPIED;
4325                        else
4326                                p->status = DIFF_STATUS_RENAMED;
4327                }
4328                else if (hashcmp(p->one->sha1, p->two->sha1) ||
4329                         p->one->mode != p->two->mode ||
4330                         p->one->dirty_submodule ||
4331                         p->two->dirty_submodule ||
4332                         is_null_sha1(p->one->sha1))
4333                        p->status = DIFF_STATUS_MODIFIED;
4334                else {
4335                        /* This is a "no-change" entry and should not
4336                         * happen anymore, but prepare for broken callers.
4337                         */
4338                        error("feeding unmodified %s to diffcore",
4339                              p->one->path);
4340                        p->status = DIFF_STATUS_UNKNOWN;
4341                }
4342        }
4343        diff_debug_queue("resolve-rename-copy done", q);
4344}
4345
4346static int check_pair_status(struct diff_filepair *p)
4347{
4348        switch (p->status) {
4349        case DIFF_STATUS_UNKNOWN:
4350                return 0;
4351        case 0:
4352                die("internal error in diff-resolve-rename-copy");
4353        default:
4354                return 1;
4355        }
4356}
4357
4358static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
4359{
4360        int fmt = opt->output_format;
4361
4362        if (fmt & DIFF_FORMAT_CHECKDIFF)
4363                diff_flush_checkdiff(p, opt);
4364        else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
4365                diff_flush_raw(p, opt);
4366        else if (fmt & DIFF_FORMAT_NAME) {
4367                const char *name_a, *name_b;
4368                name_a = p->two->path;
4369                name_b = NULL;
4370                strip_prefix(opt->prefix_length, &name_a, &name_b);
4371                write_name_quoted(name_a, opt->file, opt->line_termination);
4372        }
4373}
4374
4375static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
4376{
4377        if (fs->mode)
4378                fprintf(file, " %s mode %06o ", newdelete, fs->mode);
4379        else
4380                fprintf(file, " %s ", newdelete);
4381        write_name_quoted(fs->path, file, '\n');
4382}
4383
4384
4385static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name,
4386                const char *line_prefix)
4387{
4388        if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
4389                fprintf(file, "%s mode change %06o => %06o%c", line_prefix, p->one->mode,
4390                        p->two->mode, show_name ? ' ' : '\n');
4391                if (show_name) {
4392                        write_name_quoted(p->two->path, file, '\n');
4393                }
4394        }
4395}
4396
4397static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p,
4398                        const char *line_prefix)
4399{
4400        char *names = pprint_rename(p->one->path, p->two->path);
4401
4402        fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
4403        free(names);
4404        show_mode_change(file, p, 0, line_prefix);
4405}
4406
4407static void diff_summary(struct diff_options *opt, struct diff_filepair *p)
4408{
4409        FILE *file = opt->file;
4410        const char *line_prefix = diff_line_prefix(opt);
4411
4412        switch(p->status) {
4413        case DIFF_STATUS_DELETED:
4414                fputs(line_prefix, file);
4415                show_file_mode_name(file, "delete", p->one);
4416                break;
4417        case DIFF_STATUS_ADDED:
4418                fputs(line_prefix, file);
4419                show_file_mode_name(file, "create", p->two);
4420                break;
4421        case DIFF_STATUS_COPIED:
4422                fputs(line_prefix, file);
4423                show_rename_copy(file, "copy", p, line_prefix);
4424                break;
4425        case DIFF_STATUS_RENAMED:
4426                fputs(line_prefix, file);
4427                show_rename_copy(file, "rename", p, line_prefix);
4428                break;
4429        default:
4430                if (p->score) {
4431                        fprintf(file, "%s rewrite ", line_prefix);
4432                        write_name_quoted(p->two->path, file, ' ');
4433                        fprintf(file, "(%d%%)\n", similarity_index(p));
4434                }
4435                show_mode_change(file, p, !p->score, line_prefix);
4436                break;
4437        }
4438}
4439
4440struct patch_id_t {
4441        git_SHA_CTX *ctx;
4442        int patchlen;
4443};
4444
4445static int remove_space(char *line, int len)
4446{
4447        int i;
4448        char *dst = line;
4449        unsigned char c;
4450
4451        for (i = 0; i < len; i++)
4452                if (!isspace((c = line[i])))
4453                        *dst++ = c;
4454
4455        return dst - line;
4456}
4457
4458static void patch_id_consume(void *priv, char *line, unsigned long len)
4459{
4460        struct patch_id_t *data = priv;
4461        int new_len;
4462
4463        /* Ignore line numbers when computing the SHA1 of the patch */
4464        if (starts_with(line, "@@ -"))
4465                return;
4466
4467        new_len = remove_space(line, len);
4468
4469        git_SHA1_Update(data->ctx, line, new_len);
4470        data->patchlen += new_len;
4471}
4472
4473/* returns 0 upon success, and writes result into sha1 */
4474static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
4475{
4476        struct diff_queue_struct *q = &diff_queued_diff;
4477        int i;
4478        git_SHA_CTX ctx;
4479        struct patch_id_t data;
4480        char buffer[PATH_MAX * 4 + 20];
4481
4482        git_SHA1_Init(&ctx);
4483        memset(&data, 0, sizeof(struct patch_id_t));
4484        data.ctx = &ctx;
4485
4486        for (i = 0; i < q->nr; i++) {
4487                xpparam_t xpp;
4488                xdemitconf_t xecfg;
4489                mmfile_t mf1, mf2;
4490                struct diff_filepair *p = q->queue[i];
4491                int len1, len2;
4492
4493                memset(&xpp, 0, sizeof(xpp));
4494                memset(&xecfg, 0, sizeof(xecfg));
4495                if (p->status == 0)
4496                        return error("internal diff status error");
4497                if (p->status == DIFF_STATUS_UNKNOWN)
4498                        continue;
4499                if (diff_unmodified_pair(p))
4500                        continue;
4501                if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
4502                    (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
4503                        continue;
4504                if (DIFF_PAIR_UNMERGED(p))
4505                        continue;
4506
4507                diff_fill_sha1_info(p->one);
4508                diff_fill_sha1_info(p->two);
4509                if (fill_mmfile(&mf1, p->one) < 0 ||
4510                                fill_mmfile(&mf2, p->two) < 0)
4511                        return error("unable to read files to diff");
4512
4513                len1 = remove_space(p->one->path, strlen(p->one->path));
4514                len2 = remove_space(p->two->path, strlen(p->two->path));
4515                if (p->one->mode == 0)
4516                        len1 = snprintf(buffer, sizeof(buffer),
4517                                        "diff--gita/%.*sb/%.*s"
4518                                        "newfilemode%06o"
4519                                        "---/dev/null"
4520                                        "+++b/%.*s",
4521                                        len1, p->one->path,
4522                                        len2, p->two->path,
4523                                        p->two->mode,
4524                                        len2, p->two->path);
4525                else if (p->two->mode == 0)
4526                        len1 = snprintf(buffer, sizeof(buffer),
4527                                        "diff--gita/%.*sb/%.*s"
4528                                        "deletedfilemode%06o"
4529                                        "---a/%.*s"
4530                                        "+++/dev/null",
4531                                        len1, p->one->path,
4532                                        len2, p->two->path,
4533                                        p->one->mode,
4534                                        len1, p->one->path);
4535                else
4536                        len1 = snprintf(buffer, sizeof(buffer),
4537                                        "diff--gita/%.*sb/%.*s"
4538                                        "---a/%.*s"
4539                                        "+++b/%.*s",
4540                                        len1, p->one->path,
4541                                        len2, p->two->path,
4542                                        len1, p->one->path,
4543                                        len2, p->two->path);
4544                git_SHA1_Update(&ctx, buffer, len1);
4545
4546                if (diff_filespec_is_binary(p->one) ||
4547                    diff_filespec_is_binary(p->two)) {
4548                        git_SHA1_Update(&ctx, sha1_to_hex(p->one->sha1), 40);
4549                        git_SHA1_Update(&ctx, sha1_to_hex(p->two->sha1), 40);
4550                        continue;
4551                }
4552
4553                xpp.flags = 0;
4554                xecfg.ctxlen = 3;
4555                xecfg.flags = 0;
4556                if (xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
4557                                  &xpp, &xecfg))
4558                        return error("unable to generate patch-id diff for %s",
4559                                     p->one->path);
4560        }
4561
4562        git_SHA1_Final(sha1, &ctx);
4563        return 0;
4564}
4565
4566int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
4567{
4568        struct diff_queue_struct *q = &diff_queued_diff;
4569        int i;
4570        int result = diff_get_patch_id(options, sha1);
4571
4572        for (i = 0; i < q->nr; i++)
4573                diff_free_filepair(q->queue[i]);
4574
4575        free(q->queue);
4576        DIFF_QUEUE_CLEAR(q);
4577
4578        return result;
4579}
4580
4581static int is_summary_empty(const struct diff_queue_struct *q)
4582{
4583        int i;
4584
4585        for (i = 0; i < q->nr; i++) {
4586                const struct diff_filepair *p = q->queue[i];
4587
4588                switch (p->status) {
4589                case DIFF_STATUS_DELETED:
4590                case DIFF_STATUS_ADDED:
4591                case DIFF_STATUS_COPIED:
4592                case DIFF_STATUS_RENAMED:
4593                        return 0;
4594                default:
4595                        if (p->score)
4596                                return 0;
4597                        if (p->one->mode && p->two->mode &&
4598                            p->one->mode != p->two->mode)
4599                                return 0;
4600                        break;
4601                }
4602        }
4603        return 1;
4604}
4605
4606static const char rename_limit_warning[] =
4607"inexact rename detection was skipped due to too many files.";
4608
4609static const char degrade_cc_to_c_warning[] =
4610"only found copies from modified paths due to too many files.";
4611
4612static const char rename_limit_advice[] =
4613"you may want to set your %s variable to at least "
4614"%d and retry the command.";
4615
4616void diff_warn_rename_limit(const char *varname, int needed, int degraded_cc)
4617{
4618        if (degraded_cc)
4619                warning(degrade_cc_to_c_warning);
4620        else if (needed)
4621                warning(rename_limit_warning);
4622        else
4623                return;
4624        if (0 < needed && needed < 32767)
4625                warning(rename_limit_advice, varname, needed);
4626}
4627
4628void diff_flush(struct diff_options *options)
4629{
4630        struct diff_queue_struct *q = &diff_queued_diff;
4631        int i, output_format = options->output_format;
4632        int separator = 0;
4633        int dirstat_by_line = 0;
4634
4635        /*
4636         * Order: raw, stat, summary, patch
4637         * or:    name/name-status/checkdiff (other bits clear)
4638         */
4639        if (!q->nr)
4640                goto free_queue;
4641
4642        if (output_format & (DIFF_FORMAT_RAW |
4643                             DIFF_FORMAT_NAME |
4644                             DIFF_FORMAT_NAME_STATUS |
4645                             DIFF_FORMAT_CHECKDIFF)) {
4646                for (i = 0; i < q->nr; i++) {
4647                        struct diff_filepair *p = q->queue[i];
4648                        if (check_pair_status(p))
4649                                flush_one_pair(p, options);
4650                }
4651                separator++;
4652        }
4653
4654        if (output_format & DIFF_FORMAT_DIRSTAT && DIFF_OPT_TST(options, DIRSTAT_BY_LINE))
4655                dirstat_by_line = 1;
4656
4657        if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT) ||
4658            dirstat_by_line) {
4659                struct diffstat_t diffstat;
4660
4661                memset(&diffstat, 0, sizeof(struct diffstat_t));
4662                for (i = 0; i < q->nr; i++) {
4663                        struct diff_filepair *p = q->queue[i];
4664                        if (check_pair_status(p))
4665                                diff_flush_stat(p, options, &diffstat);
4666                }
4667                if (output_format & DIFF_FORMAT_NUMSTAT)
4668                        show_numstat(&diffstat, options);
4669                if (output_format & DIFF_FORMAT_DIFFSTAT)
4670                        show_stats(&diffstat, options);
4671                if (output_format & DIFF_FORMAT_SHORTSTAT)
4672                        show_shortstats(&diffstat, options);
4673                if (output_format & DIFF_FORMAT_DIRSTAT && dirstat_by_line)
4674                        show_dirstat_by_line(&diffstat, options);
4675                free_diffstat_info(&diffstat);
4676                separator++;
4677        }
4678        if ((output_format & DIFF_FORMAT_DIRSTAT) && !dirstat_by_line)
4679                show_dirstat(options);
4680
4681        if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
4682                for (i = 0; i < q->nr; i++) {
4683                        diff_summary(options, q->queue[i]);
4684                }
4685                separator++;
4686        }
4687
4688        if (output_format & DIFF_FORMAT_NO_OUTPUT &&
4689            DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
4690            DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4691                /*
4692                 * run diff_flush_patch for the exit status. setting
4693                 * options->file to /dev/null should be safe, because we
4694                 * aren't supposed to produce any output anyway.
4695                 */
4696                if (options->close_file)
4697                        fclose(options->file);
4698                options->file = fopen("/dev/null", "w");
4699                if (!options->file)
4700                        die_errno("Could not open /dev/null");
4701                options->close_file = 1;
4702                for (i = 0; i < q->nr; i++) {
4703                        struct diff_filepair *p = q->queue[i];
4704                        if (check_pair_status(p))
4705                                diff_flush_patch(p, options);
4706                        if (options->found_changes)
4707                                break;
4708                }
4709        }
4710
4711        if (output_format & DIFF_FORMAT_PATCH) {
4712                if (separator) {
4713                        fprintf(options->file, "%s%c",
4714                                diff_line_prefix(options),
4715                                options->line_termination);
4716                        if (options->stat_sep) {
4717                                /* attach patch instead of inline */
4718                                fputs(options->stat_sep, options->file);
4719                        }
4720                }
4721
4722                for (i = 0; i < q->nr; i++) {
4723                        struct diff_filepair *p = q->queue[i];
4724                        if (check_pair_status(p))
4725                                diff_flush_patch(p, options);
4726                }
4727        }
4728
4729        if (output_format & DIFF_FORMAT_CALLBACK)
4730                options->format_callback(q, options, options->format_callback_data);
4731
4732        for (i = 0; i < q->nr; i++)
4733                diff_free_filepair(q->queue[i]);
4734free_queue:
4735        free(q->queue);
4736        DIFF_QUEUE_CLEAR(q);
4737        if (options->close_file)
4738                fclose(options->file);
4739
4740        /*
4741         * Report the content-level differences with HAS_CHANGES;
4742         * diff_addremove/diff_change does not set the bit when
4743         * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
4744         */
4745        if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
4746                if (options->found_changes)
4747                        DIFF_OPT_SET(options, HAS_CHANGES);
4748                else
4749                        DIFF_OPT_CLR(options, HAS_CHANGES);
4750        }
4751}
4752
4753static int match_filter(const struct diff_options *options, const struct diff_filepair *p)
4754{
4755        return (((p->status == DIFF_STATUS_MODIFIED) &&
4756                 ((p->score &&
4757                   filter_bit_tst(DIFF_STATUS_FILTER_BROKEN, options)) ||
4758                  (!p->score &&
4759                   filter_bit_tst(DIFF_STATUS_MODIFIED, options)))) ||
4760                ((p->status != DIFF_STATUS_MODIFIED) &&
4761                 filter_bit_tst(p->status, options)));
4762}
4763
4764static void diffcore_apply_filter(struct diff_options *options)
4765{
4766        int i;
4767        struct diff_queue_struct *q = &diff_queued_diff;
4768        struct diff_queue_struct outq;
4769
4770        DIFF_QUEUE_CLEAR(&outq);
4771
4772        if (!options->filter)
4773                return;
4774
4775        if (filter_bit_tst(DIFF_STATUS_FILTER_AON, options)) {
4776                int found;
4777                for (i = found = 0; !found && i < q->nr; i++) {
4778                        if (match_filter(options, q->queue[i]))
4779                                found++;
4780                }
4781                if (found)
4782                        return;
4783
4784                /* otherwise we will clear the whole queue
4785                 * by copying the empty outq at the end of this
4786                 * function, but first clear the current entries
4787                 * in the queue.
4788                 */
4789                for (i = 0; i < q->nr; i++)
4790                        diff_free_filepair(q->queue[i]);
4791        }
4792        else {
4793                /* Only the matching ones */
4794                for (i = 0; i < q->nr; i++) {
4795                        struct diff_filepair *p = q->queue[i];
4796                        if (match_filter(options, p))
4797                                diff_q(&outq, p);
4798                        else
4799                                diff_free_filepair(p);
4800                }
4801        }
4802        free(q->queue);
4803        *q = outq;
4804}
4805
4806/* Check whether two filespecs with the same mode and size are identical */
4807static int diff_filespec_is_identical(struct diff_filespec *one,
4808                                      struct diff_filespec *two)
4809{
4810        if (S_ISGITLINK(one->mode))
4811                return 0;
4812        if (diff_populate_filespec(one, 0))
4813                return 0;
4814        if (diff_populate_filespec(two, 0))
4815                return 0;
4816        return !memcmp(one->data, two->data, one->size);
4817}
4818
4819static int diff_filespec_check_stat_unmatch(struct diff_filepair *p)
4820{
4821        if (p->done_skip_stat_unmatch)
4822                return p->skip_stat_unmatch_result;
4823
4824        p->done_skip_stat_unmatch = 1;
4825        p->skip_stat_unmatch_result = 0;
4826        /*
4827         * 1. Entries that come from stat info dirtiness
4828         *    always have both sides (iow, not create/delete),
4829         *    one side of the object name is unknown, with
4830         *    the same mode and size.  Keep the ones that
4831         *    do not match these criteria.  They have real
4832         *    differences.
4833         *
4834         * 2. At this point, the file is known to be modified,
4835         *    with the same mode and size, and the object
4836         *    name of one side is unknown.  Need to inspect
4837         *    the identical contents.
4838         */
4839        if (!DIFF_FILE_VALID(p->one) || /* (1) */
4840            !DIFF_FILE_VALID(p->two) ||
4841            (p->one->sha1_valid && p->two->sha1_valid) ||
4842            (p->one->mode != p->two->mode) ||
4843            diff_populate_filespec(p->one, CHECK_SIZE_ONLY) ||
4844            diff_populate_filespec(p->two, CHECK_SIZE_ONLY) ||
4845            (p->one->size != p->two->size) ||
4846            !diff_filespec_is_identical(p->one, p->two)) /* (2) */
4847                p->skip_stat_unmatch_result = 1;
4848        return p->skip_stat_unmatch_result;
4849}
4850
4851static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
4852{
4853        int i;
4854        struct diff_queue_struct *q = &diff_queued_diff;
4855        struct diff_queue_struct outq;
4856        DIFF_QUEUE_CLEAR(&outq);
4857
4858        for (i = 0; i < q->nr; i++) {
4859                struct diff_filepair *p = q->queue[i];
4860
4861                if (diff_filespec_check_stat_unmatch(p))
4862                        diff_q(&outq, p);
4863                else {
4864                        /*
4865                         * The caller can subtract 1 from skip_stat_unmatch
4866                         * to determine how many paths were dirty only
4867                         * due to stat info mismatch.
4868                         */
4869                        if (!DIFF_OPT_TST(diffopt, NO_INDEX))
4870                                diffopt->skip_stat_unmatch++;
4871                        diff_free_filepair(p);
4872                }
4873        }
4874        free(q->queue);
4875        *q = outq;
4876}
4877
4878static int diffnamecmp(const void *a_, const void *b_)
4879{
4880        const struct diff_filepair *a = *((const struct diff_filepair **)a_);
4881        const struct diff_filepair *b = *((const struct diff_filepair **)b_);
4882        const char *name_a, *name_b;
4883
4884        name_a = a->one ? a->one->path : a->two->path;
4885        name_b = b->one ? b->one->path : b->two->path;
4886        return strcmp(name_a, name_b);
4887}
4888
4889void diffcore_fix_diff_index(struct diff_options *options)
4890{
4891        struct diff_queue_struct *q = &diff_queued_diff;
4892        qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
4893}
4894
4895void diffcore_std(struct diff_options *options)
4896{
4897        /* NOTE please keep the following in sync with diff_tree_combined() */
4898        if (options->skip_stat_unmatch)
4899                diffcore_skip_stat_unmatch(options);
4900        if (!options->found_follow) {
4901                /* See try_to_follow_renames() in tree-diff.c */
4902                if (options->break_opt != -1)
4903                        diffcore_break(options->break_opt);
4904                if (options->detect_rename)
4905                        diffcore_rename(options);
4906                if (options->break_opt != -1)
4907                        diffcore_merge_broken();
4908        }
4909        if (options->pickaxe)
4910                diffcore_pickaxe(options);
4911        if (options->orderfile)
4912                diffcore_order(options->orderfile);
4913        if (!options->found_follow)
4914                /* See try_to_follow_renames() in tree-diff.c */
4915                diff_resolve_rename_copy();
4916        diffcore_apply_filter(options);
4917
4918        if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
4919                DIFF_OPT_SET(options, HAS_CHANGES);
4920        else
4921                DIFF_OPT_CLR(options, HAS_CHANGES);
4922
4923        options->found_follow = 0;
4924}
4925
4926int diff_result_code(struct diff_options *opt, int status)
4927{
4928        int result = 0;
4929
4930        diff_warn_rename_limit("diff.renameLimit",
4931                               opt->needed_rename_limit,
4932                               opt->degraded_cc_to_c);
4933        if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4934            !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
4935                return status;
4936        if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
4937            DIFF_OPT_TST(opt, HAS_CHANGES))
4938                result |= 01;
4939        if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
4940            DIFF_OPT_TST(opt, CHECK_FAILED))
4941                result |= 02;
4942        return result;
4943}
4944
4945int diff_can_quit_early(struct diff_options *opt)
4946{
4947        return (DIFF_OPT_TST(opt, QUICK) &&
4948                !opt->filter &&
4949                DIFF_OPT_TST(opt, HAS_CHANGES));
4950}
4951
4952/*
4953 * Shall changes to this submodule be ignored?
4954 *
4955 * Submodule changes can be configured to be ignored separately for each path,
4956 * but that configuration can be overridden from the command line.
4957 */
4958static int is_submodule_ignored(const char *path, struct diff_options *options)
4959{
4960        int ignored = 0;
4961        unsigned orig_flags = options->flags;
4962        if (!DIFF_OPT_TST(options, OVERRIDE_SUBMODULE_CONFIG))
4963                set_diffopt_flags_from_submodule_config(options, path);
4964        if (DIFF_OPT_TST(options, IGNORE_SUBMODULES))
4965                ignored = 1;
4966        options->flags = orig_flags;
4967        return ignored;
4968}
4969
4970void diff_addremove(struct diff_options *options,
4971                    int addremove, unsigned mode,
4972                    const unsigned char *sha1,
4973                    int sha1_valid,
4974                    const char *concatpath, unsigned dirty_submodule)
4975{
4976        struct diff_filespec *one, *two;
4977
4978        if (S_ISGITLINK(mode) && is_submodule_ignored(concatpath, options))
4979                return;
4980
4981        /* This may look odd, but it is a preparation for
4982         * feeding "there are unchanged files which should
4983         * not produce diffs, but when you are doing copy
4984         * detection you would need them, so here they are"
4985         * entries to the diff-core.  They will be prefixed
4986         * with something like '=' or '*' (I haven't decided
4987         * which but should not make any difference).
4988         * Feeding the same new and old to diff_change()
4989         * also has the same effect.
4990         * Before the final output happens, they are pruned after
4991         * merged into rename/copy pairs as appropriate.
4992         */
4993        if (DIFF_OPT_TST(options, REVERSE_DIFF))
4994                addremove = (addremove == '+' ? '-' :
4995                             addremove == '-' ? '+' : addremove);
4996
4997        if (options->prefix &&
4998            strncmp(concatpath, options->prefix, options->prefix_length))
4999                return;
5000
5001        one = alloc_filespec(concatpath);
5002        two = alloc_filespec(concatpath);
5003
5004        if (addremove != '+')
5005                fill_filespec(one, sha1, sha1_valid, mode);
5006        if (addremove != '-') {
5007                fill_filespec(two, sha1, sha1_valid, mode);
5008                two->dirty_submodule = dirty_submodule;
5009        }
5010
5011        diff_queue(&diff_queued_diff, one, two);
5012        if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5013                DIFF_OPT_SET(options, HAS_CHANGES);
5014}
5015
5016void diff_change(struct diff_options *options,
5017                 unsigned old_mode, unsigned new_mode,
5018                 const unsigned char *old_sha1,
5019                 const unsigned char *new_sha1,
5020                 int old_sha1_valid, int new_sha1_valid,
5021                 const char *concatpath,
5022                 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
5023{
5024        struct diff_filespec *one, *two;
5025        struct diff_filepair *p;
5026
5027        if (S_ISGITLINK(old_mode) && S_ISGITLINK(new_mode) &&
5028            is_submodule_ignored(concatpath, options))
5029                return;
5030
5031        if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
5032                unsigned tmp;
5033                const unsigned char *tmp_c;
5034                tmp = old_mode; old_mode = new_mode; new_mode = tmp;
5035                tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
5036                tmp = old_sha1_valid; old_sha1_valid = new_sha1_valid;
5037                        new_sha1_valid = tmp;
5038                tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
5039                        new_dirty_submodule = tmp;
5040        }
5041
5042        if (options->prefix &&
5043            strncmp(concatpath, options->prefix, options->prefix_length))
5044                return;
5045
5046        one = alloc_filespec(concatpath);
5047        two = alloc_filespec(concatpath);
5048        fill_filespec(one, old_sha1, old_sha1_valid, old_mode);
5049        fill_filespec(two, new_sha1, new_sha1_valid, new_mode);
5050        one->dirty_submodule = old_dirty_submodule;
5051        two->dirty_submodule = new_dirty_submodule;
5052        p = diff_queue(&diff_queued_diff, one, two);
5053
5054        if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
5055                return;
5056
5057        if (DIFF_OPT_TST(options, QUICK) && options->skip_stat_unmatch &&
5058            !diff_filespec_check_stat_unmatch(p))
5059                return;
5060
5061        DIFF_OPT_SET(options, HAS_CHANGES);
5062}
5063
5064struct diff_filepair *diff_unmerge(struct diff_options *options, const char *path)
5065{
5066        struct diff_filepair *pair;
5067        struct diff_filespec *one, *two;
5068
5069        if (options->prefix &&
5070            strncmp(path, options->prefix, options->prefix_length))
5071                return NULL;
5072
5073        one = alloc_filespec(path);
5074        two = alloc_filespec(path);
5075        pair = diff_queue(&diff_queued_diff, one, two);
5076        pair->is_unmerged = 1;
5077        return pair;
5078}
5079
5080static char *run_textconv(const char *pgm, struct diff_filespec *spec,
5081                size_t *outsize)
5082{
5083        struct diff_tempfile *temp;
5084        const char *argv[3];
5085        const char **arg = argv;
5086        struct child_process child = CHILD_PROCESS_INIT;
5087        struct strbuf buf = STRBUF_INIT;
5088        int err = 0;
5089
5090        temp = prepare_temp_file(spec->path, spec);
5091        *arg++ = pgm;
5092        *arg++ = temp->name;
5093        *arg = NULL;
5094
5095        child.use_shell = 1;
5096        child.argv = argv;
5097        child.out = -1;
5098        if (start_command(&child)) {
5099                remove_tempfile();
5100                return NULL;
5101        }
5102
5103        if (strbuf_read(&buf, child.out, 0) < 0)
5104                err = error("error reading from textconv command '%s'", pgm);
5105        close(child.out);
5106
5107        if (finish_command(&child) || err) {
5108                strbuf_release(&buf);
5109                remove_tempfile();
5110                return NULL;
5111        }
5112        remove_tempfile();
5113
5114        return strbuf_detach(&buf, outsize);
5115}
5116
5117size_t fill_textconv(struct userdiff_driver *driver,
5118                     struct diff_filespec *df,
5119                     char **outbuf)
5120{
5121        size_t size;
5122
5123        if (!driver) {
5124                if (!DIFF_FILE_VALID(df)) {
5125                        *outbuf = "";
5126                        return 0;
5127                }
5128                if (diff_populate_filespec(df, 0))
5129                        die("unable to read files to diff");
5130                *outbuf = df->data;
5131                return df->size;
5132        }
5133
5134        if (!driver->textconv)
5135                die("BUG: fill_textconv called with non-textconv driver");
5136
5137        if (driver->textconv_cache && df->sha1_valid) {
5138                *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
5139                                          &size);
5140                if (*outbuf)
5141                        return size;
5142        }
5143
5144        *outbuf = run_textconv(driver->textconv, df, &size);
5145        if (!*outbuf)
5146                die("unable to read files to diff");
5147
5148        if (driver->textconv_cache && df->sha1_valid) {
5149                /* ignore errors, as we might be in a readonly repository */
5150                notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
5151                                size);
5152                /*
5153                 * we could save up changes and flush them all at the end,
5154                 * but we would need an extra call after all diffing is done.
5155                 * Since generating a cache entry is the slow path anyway,
5156                 * this extra overhead probably isn't a big deal.
5157                 */
5158                notes_cache_write(driver->textconv_cache);
5159        }
5160
5161        return size;
5162}
5163
5164void setup_diff_pager(struct diff_options *opt)
5165{
5166        /*
5167         * If the user asked for our exit code, then either they want --quiet
5168         * or --exit-code. We should definitely not bother with a pager in the
5169         * former case, as we will generate no output. Since we still properly
5170         * report our exit code even when a pager is run, we _could_ run a
5171         * pager with --exit-code. But since we have not done so historically,
5172         * and because it is easy to find people oneline advising "git diff
5173         * --exit-code" in hooks and other scripts, we do not do so.
5174         */
5175        if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
5176            check_pager_config("diff") != 0)
5177                setup_pager();
5178}