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