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