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