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