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