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