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