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