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