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