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