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