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