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