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