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