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