diff.con commit Merge branch 'rs/diff-no-minimal' (39b5977)
   1/*
   2 * Copyright (C) 2005 Junio C Hamano
   3 */
   4#include "cache.h"
   5#include "quote.h"
   6#include "diff.h"
   7#include "diffcore.h"
   8#include "delta.h"
   9#include "xdiff-interface.h"
  10#include "color.h"
  11#include "attr.h"
  12#include "run-command.h"
  13#include "utf8.h"
  14#include "userdiff.h"
  15#include "sigchain.h"
  16#include "submodule.h"
  17#include "ll-merge.h"
  18
  19#ifdef NO_FAST_WORKING_DIRECTORY
  20#define FAST_WORKING_DIRECTORY 0
  21#else
  22#define FAST_WORKING_DIRECTORY 1
  23#endif
  24
  25static int diff_detect_rename_default;
  26static int diff_rename_limit_default = 200;
  27static int diff_suppress_blank_empty;
  28int diff_use_color_default = -1;
  29static const char *diff_word_regex_cfg;
  30static const char *external_diff_cmd_cfg;
  31int diff_auto_refresh_index = 1;
  32static int diff_mnemonic_prefix;
  33
  34static char diff_colors[][COLOR_MAXLEN] = {
  35        GIT_COLOR_RESET,
  36        GIT_COLOR_NORMAL,       /* PLAIN */
  37        GIT_COLOR_BOLD,         /* METAINFO */
  38        GIT_COLOR_CYAN,         /* FRAGINFO */
  39        GIT_COLOR_RED,          /* OLD */
  40        GIT_COLOR_GREEN,        /* NEW */
  41        GIT_COLOR_YELLOW,       /* COMMIT */
  42        GIT_COLOR_BG_RED,       /* WHITESPACE */
  43        GIT_COLOR_NORMAL,       /* FUNCINFO */
  44};
  45
  46static void diff_filespec_load_driver(struct diff_filespec *one);
  47static size_t fill_textconv(struct userdiff_driver *driver,
  48                            struct diff_filespec *df, char **outbuf);
  49
  50static int parse_diff_color_slot(const char *var, int ofs)
  51{
  52        if (!strcasecmp(var+ofs, "plain"))
  53                return DIFF_PLAIN;
  54        if (!strcasecmp(var+ofs, "meta"))
  55                return DIFF_METAINFO;
  56        if (!strcasecmp(var+ofs, "frag"))
  57                return DIFF_FRAGINFO;
  58        if (!strcasecmp(var+ofs, "old"))
  59                return DIFF_FILE_OLD;
  60        if (!strcasecmp(var+ofs, "new"))
  61                return DIFF_FILE_NEW;
  62        if (!strcasecmp(var+ofs, "commit"))
  63                return DIFF_COMMIT;
  64        if (!strcasecmp(var+ofs, "whitespace"))
  65                return DIFF_WHITESPACE;
  66        if (!strcasecmp(var+ofs, "func"))
  67                return DIFF_FUNCINFO;
  68        return -1;
  69}
  70
  71static int git_config_rename(const char *var, const char *value)
  72{
  73        if (!value)
  74                return DIFF_DETECT_RENAME;
  75        if (!strcasecmp(value, "copies") || !strcasecmp(value, "copy"))
  76                return  DIFF_DETECT_COPY;
  77        return git_config_bool(var,value) ? DIFF_DETECT_RENAME : 0;
  78}
  79
  80/*
  81 * These are to give UI layer defaults.
  82 * The core-level commands such as git-diff-files should
  83 * never be affected by the setting of diff.renames
  84 * the user happens to have in the configuration file.
  85 */
  86int git_diff_ui_config(const char *var, const char *value, void *cb)
  87{
  88        if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
  89                diff_use_color_default = git_config_colorbool(var, value, -1);
  90                return 0;
  91        }
  92        if (!strcmp(var, "diff.renames")) {
  93                diff_detect_rename_default = git_config_rename(var, value);
  94                return 0;
  95        }
  96        if (!strcmp(var, "diff.autorefreshindex")) {
  97                diff_auto_refresh_index = git_config_bool(var, value);
  98                return 0;
  99        }
 100        if (!strcmp(var, "diff.mnemonicprefix")) {
 101                diff_mnemonic_prefix = git_config_bool(var, value);
 102                return 0;
 103        }
 104        if (!strcmp(var, "diff.external"))
 105                return git_config_string(&external_diff_cmd_cfg, var, value);
 106        if (!strcmp(var, "diff.wordregex"))
 107                return git_config_string(&diff_word_regex_cfg, var, value);
 108
 109        return git_diff_basic_config(var, value, cb);
 110}
 111
 112int git_diff_basic_config(const char *var, const char *value, void *cb)
 113{
 114        if (!strcmp(var, "diff.renamelimit")) {
 115                diff_rename_limit_default = git_config_int(var, value);
 116                return 0;
 117        }
 118
 119        switch (userdiff_config(var, value)) {
 120                case 0: break;
 121                case -1: return -1;
 122                default: return 0;
 123        }
 124
 125        if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
 126                int slot = parse_diff_color_slot(var, 11);
 127                if (slot < 0)
 128                        return 0;
 129                if (!value)
 130                        return config_error_nonbool(var);
 131                color_parse(value, var, diff_colors[slot]);
 132                return 0;
 133        }
 134
 135        /* like GNU diff's --suppress-blank-empty option  */
 136        if (!strcmp(var, "diff.suppressblankempty") ||
 137                        /* for backwards compatibility */
 138                        !strcmp(var, "diff.suppress-blank-empty")) {
 139                diff_suppress_blank_empty = git_config_bool(var, value);
 140                return 0;
 141        }
 142
 143        return git_color_default_config(var, value, cb);
 144}
 145
 146static char *quote_two(const char *one, const char *two)
 147{
 148        int need_one = quote_c_style(one, NULL, NULL, 1);
 149        int need_two = quote_c_style(two, NULL, NULL, 1);
 150        struct strbuf res = STRBUF_INIT;
 151
 152        if (need_one + need_two) {
 153                strbuf_addch(&res, '"');
 154                quote_c_style(one, &res, NULL, 1);
 155                quote_c_style(two, &res, NULL, 1);
 156                strbuf_addch(&res, '"');
 157        } else {
 158                strbuf_addstr(&res, one);
 159                strbuf_addstr(&res, two);
 160        }
 161        return strbuf_detach(&res, NULL);
 162}
 163
 164static const char *external_diff(void)
 165{
 166        static const char *external_diff_cmd = NULL;
 167        static int done_preparing = 0;
 168
 169        if (done_preparing)
 170                return external_diff_cmd;
 171        external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
 172        if (!external_diff_cmd)
 173                external_diff_cmd = external_diff_cmd_cfg;
 174        done_preparing = 1;
 175        return external_diff_cmd;
 176}
 177
 178static struct diff_tempfile {
 179        const char *name; /* filename external diff should read from */
 180        char hex[41];
 181        char mode[10];
 182        char tmp_path[PATH_MAX];
 183} diff_temp[2];
 184
 185typedef unsigned long (*sane_truncate_fn)(char *line, unsigned long len);
 186
 187struct emit_callback {
 188        int color_diff;
 189        unsigned ws_rule;
 190        int blank_at_eof_in_preimage;
 191        int blank_at_eof_in_postimage;
 192        int lno_in_preimage;
 193        int lno_in_postimage;
 194        sane_truncate_fn truncate;
 195        const char **label_path;
 196        struct diff_words_data *diff_words;
 197        int *found_changesp;
 198        FILE *file;
 199        struct strbuf *header;
 200};
 201
 202static int count_lines(const char *data, int size)
 203{
 204        int count, ch, completely_empty = 1, nl_just_seen = 0;
 205        count = 0;
 206        while (0 < size--) {
 207                ch = *data++;
 208                if (ch == '\n') {
 209                        count++;
 210                        nl_just_seen = 1;
 211                        completely_empty = 0;
 212                }
 213                else {
 214                        nl_just_seen = 0;
 215                        completely_empty = 0;
 216                }
 217        }
 218        if (completely_empty)
 219                return 0;
 220        if (!nl_just_seen)
 221                count++; /* no trailing newline */
 222        return count;
 223}
 224
 225static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
 226{
 227        if (!DIFF_FILE_VALID(one)) {
 228                mf->ptr = (char *)""; /* does not matter */
 229                mf->size = 0;
 230                return 0;
 231        }
 232        else if (diff_populate_filespec(one, 0))
 233                return -1;
 234
 235        mf->ptr = one->data;
 236        mf->size = one->size;
 237        return 0;
 238}
 239
 240static int count_trailing_blank(mmfile_t *mf, unsigned ws_rule)
 241{
 242        char *ptr = mf->ptr;
 243        long size = mf->size;
 244        int cnt = 0;
 245
 246        if (!size)
 247                return cnt;
 248        ptr += size - 1; /* pointing at the very end */
 249        if (*ptr != '\n')
 250                ; /* incomplete line */
 251        else
 252                ptr--; /* skip the last LF */
 253        while (mf->ptr < ptr) {
 254                char *prev_eol;
 255                for (prev_eol = ptr; mf->ptr <= prev_eol; prev_eol--)
 256                        if (*prev_eol == '\n')
 257                                break;
 258                if (!ws_blank_line(prev_eol + 1, ptr - prev_eol, ws_rule))
 259                        break;
 260                cnt++;
 261                ptr = prev_eol - 1;
 262        }
 263        return cnt;
 264}
 265
 266static void check_blank_at_eof(mmfile_t *mf1, mmfile_t *mf2,
 267                               struct emit_callback *ecbdata)
 268{
 269        int l1, l2, at;
 270        unsigned ws_rule = ecbdata->ws_rule;
 271        l1 = count_trailing_blank(mf1, ws_rule);
 272        l2 = count_trailing_blank(mf2, ws_rule);
 273        if (l2 <= l1) {
 274                ecbdata->blank_at_eof_in_preimage = 0;
 275                ecbdata->blank_at_eof_in_postimage = 0;
 276                return;
 277        }
 278        at = count_lines(mf1->ptr, mf1->size);
 279        ecbdata->blank_at_eof_in_preimage = (at - l1) + 1;
 280
 281        at = count_lines(mf2->ptr, mf2->size);
 282        ecbdata->blank_at_eof_in_postimage = (at - l2) + 1;
 283}
 284
 285static void emit_line_0(FILE *file, const char *set, const char *reset,
 286                        int first, const char *line, int len)
 287{
 288        int has_trailing_newline, has_trailing_carriage_return;
 289        int nofirst;
 290
 291        if (len == 0) {
 292                has_trailing_newline = (first == '\n');
 293                has_trailing_carriage_return = (!has_trailing_newline &&
 294                                                (first == '\r'));
 295                nofirst = has_trailing_newline || has_trailing_carriage_return;
 296        } else {
 297                has_trailing_newline = (len > 0 && line[len-1] == '\n');
 298                if (has_trailing_newline)
 299                        len--;
 300                has_trailing_carriage_return = (len > 0 && line[len-1] == '\r');
 301                if (has_trailing_carriage_return)
 302                        len--;
 303                nofirst = 0;
 304        }
 305
 306        if (len || !nofirst) {
 307                fputs(set, file);
 308                if (!nofirst)
 309                        fputc(first, file);
 310                fwrite(line, len, 1, file);
 311                fputs(reset, file);
 312        }
 313        if (has_trailing_carriage_return)
 314                fputc('\r', file);
 315        if (has_trailing_newline)
 316                fputc('\n', file);
 317}
 318
 319static void emit_line(FILE *file, const char *set, const char *reset,
 320                      const char *line, int len)
 321{
 322        emit_line_0(file, set, reset, line[0], line+1, len-1);
 323}
 324
 325static int new_blank_line_at_eof(struct emit_callback *ecbdata, const char *line, int len)
 326{
 327        if (!((ecbdata->ws_rule & WS_BLANK_AT_EOF) &&
 328              ecbdata->blank_at_eof_in_preimage &&
 329              ecbdata->blank_at_eof_in_postimage &&
 330              ecbdata->blank_at_eof_in_preimage <= ecbdata->lno_in_preimage &&
 331              ecbdata->blank_at_eof_in_postimage <= ecbdata->lno_in_postimage))
 332                return 0;
 333        return ws_blank_line(line, len, ecbdata->ws_rule);
 334}
 335
 336static void emit_add_line(const char *reset,
 337                          struct emit_callback *ecbdata,
 338                          const char *line, int len)
 339{
 340        const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
 341        const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
 342
 343        if (!*ws)
 344                emit_line_0(ecbdata->file, set, reset, '+', line, len);
 345        else if (new_blank_line_at_eof(ecbdata, line, len))
 346                /* Blank line at EOF - paint '+' as well */
 347                emit_line_0(ecbdata->file, ws, reset, '+', line, len);
 348        else {
 349                /* Emit just the prefix, then the rest. */
 350                emit_line_0(ecbdata->file, set, reset, '+', "", 0);
 351                ws_check_emit(line, len, ecbdata->ws_rule,
 352                              ecbdata->file, set, reset, ws);
 353        }
 354}
 355
 356static void emit_hunk_header(struct emit_callback *ecbdata,
 357                             const char *line, int len)
 358{
 359        const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
 360        const char *frag = diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO);
 361        const char *func = diff_get_color(ecbdata->color_diff, DIFF_FUNCINFO);
 362        const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
 363        static const char atat[2] = { '@', '@' };
 364        const char *cp, *ep;
 365
 366        /*
 367         * As a hunk header must begin with "@@ -<old>, +<new> @@",
 368         * it always is at least 10 bytes long.
 369         */
 370        if (len < 10 ||
 371            memcmp(line, atat, 2) ||
 372            !(ep = memmem(line + 2, len - 2, atat, 2))) {
 373                emit_line(ecbdata->file, plain, reset, line, len);
 374                return;
 375        }
 376        ep += 2; /* skip over @@ */
 377
 378        /* The hunk header in fraginfo color */
 379        emit_line(ecbdata->file, frag, reset, line, ep - line);
 380
 381        /* blank before the func header */
 382        for (cp = ep; ep - line < len; ep++)
 383                if (*ep != ' ' && *ep != '\t')
 384                        break;
 385        if (ep != cp)
 386                emit_line(ecbdata->file, plain, reset, cp, ep - cp);
 387
 388        if (ep < line + len)
 389                emit_line(ecbdata->file, func, reset, ep, line + len - ep);
 390}
 391
 392static struct diff_tempfile *claim_diff_tempfile(void) {
 393        int i;
 394        for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
 395                if (!diff_temp[i].name)
 396                        return diff_temp + i;
 397        die("BUG: diff is failing to clean up its tempfiles");
 398}
 399
 400static int remove_tempfile_installed;
 401
 402static void remove_tempfile(void)
 403{
 404        int i;
 405        for (i = 0; i < ARRAY_SIZE(diff_temp); i++) {
 406                if (diff_temp[i].name == diff_temp[i].tmp_path)
 407                        unlink_or_warn(diff_temp[i].name);
 408                diff_temp[i].name = NULL;
 409        }
 410}
 411
 412static void remove_tempfile_on_signal(int signo)
 413{
 414        remove_tempfile();
 415        sigchain_pop(signo);
 416        raise(signo);
 417}
 418
 419static void print_line_count(FILE *file, int count)
 420{
 421        switch (count) {
 422        case 0:
 423                fprintf(file, "0,0");
 424                break;
 425        case 1:
 426                fprintf(file, "1");
 427                break;
 428        default:
 429                fprintf(file, "1,%d", count);
 430                break;
 431        }
 432}
 433
 434static void emit_rewrite_lines(struct emit_callback *ecb,
 435                               int prefix, const char *data, int size)
 436{
 437        const char *endp = NULL;
 438        static const char *nneof = " No newline at end of file\n";
 439        const char *old = diff_get_color(ecb->color_diff, DIFF_FILE_OLD);
 440        const char *reset = diff_get_color(ecb->color_diff, DIFF_RESET);
 441
 442        while (0 < size) {
 443                int len;
 444
 445                endp = memchr(data, '\n', size);
 446                len = endp ? (endp - data + 1) : size;
 447                if (prefix != '+') {
 448                        ecb->lno_in_preimage++;
 449                        emit_line_0(ecb->file, old, reset, '-',
 450                                    data, len);
 451                } else {
 452                        ecb->lno_in_postimage++;
 453                        emit_add_line(reset, ecb, data, len);
 454                }
 455                size -= len;
 456                data += len;
 457        }
 458        if (!endp) {
 459                const char *plain = diff_get_color(ecb->color_diff,
 460                                                   DIFF_PLAIN);
 461                emit_line_0(ecb->file, plain, reset, '\\',
 462                            nneof, strlen(nneof));
 463        }
 464}
 465
 466static void emit_rewrite_diff(const char *name_a,
 467                              const char *name_b,
 468                              struct diff_filespec *one,
 469                              struct diff_filespec *two,
 470                              struct userdiff_driver *textconv_one,
 471                              struct userdiff_driver *textconv_two,
 472                              struct diff_options *o)
 473{
 474        int lc_a, lc_b;
 475        int color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
 476        const char *name_a_tab, *name_b_tab;
 477        const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
 478        const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
 479        const char *reset = diff_get_color(color_diff, DIFF_RESET);
 480        static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT;
 481        const char *a_prefix, *b_prefix;
 482        char *data_one, *data_two;
 483        size_t size_one, size_two;
 484        struct emit_callback ecbdata;
 485
 486        if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) {
 487                a_prefix = o->b_prefix;
 488                b_prefix = o->a_prefix;
 489        } else {
 490                a_prefix = o->a_prefix;
 491                b_prefix = o->b_prefix;
 492        }
 493
 494        name_a += (*name_a == '/');
 495        name_b += (*name_b == '/');
 496        name_a_tab = strchr(name_a, ' ') ? "\t" : "";
 497        name_b_tab = strchr(name_b, ' ') ? "\t" : "";
 498
 499        strbuf_reset(&a_name);
 500        strbuf_reset(&b_name);
 501        quote_two_c_style(&a_name, a_prefix, name_a, 0);
 502        quote_two_c_style(&b_name, b_prefix, name_b, 0);
 503
 504        size_one = fill_textconv(textconv_one, one, &data_one);
 505        size_two = fill_textconv(textconv_two, two, &data_two);
 506
 507        memset(&ecbdata, 0, sizeof(ecbdata));
 508        ecbdata.color_diff = color_diff;
 509        ecbdata.found_changesp = &o->found_changes;
 510        ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
 511        ecbdata.file = o->file;
 512        if (ecbdata.ws_rule & WS_BLANK_AT_EOF) {
 513                mmfile_t mf1, mf2;
 514                mf1.ptr = (char *)data_one;
 515                mf2.ptr = (char *)data_two;
 516                mf1.size = size_one;
 517                mf2.size = size_two;
 518                check_blank_at_eof(&mf1, &mf2, &ecbdata);
 519        }
 520        ecbdata.lno_in_preimage = 1;
 521        ecbdata.lno_in_postimage = 1;
 522
 523        lc_a = count_lines(data_one, size_one);
 524        lc_b = count_lines(data_two, size_two);
 525        fprintf(o->file,
 526                "%s--- %s%s%s\n%s+++ %s%s%s\n%s@@ -",
 527                metainfo, a_name.buf, name_a_tab, reset,
 528                metainfo, b_name.buf, name_b_tab, reset, fraginfo);
 529        print_line_count(o->file, lc_a);
 530        fprintf(o->file, " +");
 531        print_line_count(o->file, lc_b);
 532        fprintf(o->file, " @@%s\n", reset);
 533        if (lc_a)
 534                emit_rewrite_lines(&ecbdata, '-', data_one, size_one);
 535        if (lc_b)
 536                emit_rewrite_lines(&ecbdata, '+', data_two, size_two);
 537        if (textconv_one)
 538                free((char *)data_one);
 539        if (textconv_two)
 540                free((char *)data_two);
 541}
 542
 543struct diff_words_buffer {
 544        mmfile_t text;
 545        long alloc;
 546        struct diff_words_orig {
 547                const char *begin, *end;
 548        } *orig;
 549        int orig_nr, orig_alloc;
 550};
 551
 552static void diff_words_append(char *line, unsigned long len,
 553                struct diff_words_buffer *buffer)
 554{
 555        ALLOC_GROW(buffer->text.ptr, buffer->text.size + len, buffer->alloc);
 556        line++;
 557        len--;
 558        memcpy(buffer->text.ptr + buffer->text.size, line, len);
 559        buffer->text.size += len;
 560        buffer->text.ptr[buffer->text.size] = '\0';
 561}
 562
 563struct diff_words_style_elem
 564{
 565        const char *prefix;
 566        const char *suffix;
 567        const char *color; /* NULL; filled in by the setup code if
 568                            * color is enabled */
 569};
 570
 571struct diff_words_style
 572{
 573        enum diff_words_type type;
 574        struct diff_words_style_elem new, old, ctx;
 575        const char *newline;
 576};
 577
 578struct diff_words_style diff_words_styles[] = {
 579        { DIFF_WORDS_PORCELAIN, {"+", "\n"}, {"-", "\n"}, {" ", "\n"}, "~\n" },
 580        { DIFF_WORDS_PLAIN, {"{+", "+}"}, {"[-", "-]"}, {"", ""}, "\n" },
 581        { DIFF_WORDS_COLOR, {"", ""}, {"", ""}, {"", ""}, "\n" }
 582};
 583
 584struct diff_words_data {
 585        struct diff_words_buffer minus, plus;
 586        const char *current_plus;
 587        FILE *file;
 588        regex_t *word_regex;
 589        enum diff_words_type type;
 590        struct diff_words_style *style;
 591};
 592
 593static int fn_out_diff_words_write_helper(FILE *fp,
 594                                          struct diff_words_style_elem *st_el,
 595                                          const char *newline,
 596                                          size_t count, const char *buf)
 597{
 598        while (count) {
 599                char *p = memchr(buf, '\n', count);
 600                if (p != buf) {
 601                        if (st_el->color && fputs(st_el->color, fp) < 0)
 602                                return -1;
 603                        if (fputs(st_el->prefix, fp) < 0 ||
 604                            fwrite(buf, p ? p - buf : count, 1, fp) != 1 ||
 605                            fputs(st_el->suffix, fp) < 0)
 606                                return -1;
 607                        if (st_el->color && *st_el->color
 608                            && fputs(GIT_COLOR_RESET, fp) < 0)
 609                                return -1;
 610                }
 611                if (!p)
 612                        return 0;
 613                if (fputs(newline, fp) < 0)
 614                        return -1;
 615                count -= p + 1 - buf;
 616                buf = p + 1;
 617        }
 618        return 0;
 619}
 620
 621static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
 622{
 623        struct diff_words_data *diff_words = priv;
 624        struct diff_words_style *style = diff_words->style;
 625        int minus_first, minus_len, plus_first, plus_len;
 626        const char *minus_begin, *minus_end, *plus_begin, *plus_end;
 627
 628        if (line[0] != '@' || parse_hunk_header(line, len,
 629                        &minus_first, &minus_len, &plus_first, &plus_len))
 630                return;
 631
 632        /* POSIX requires that first be decremented by one if len == 0... */
 633        if (minus_len) {
 634                minus_begin = diff_words->minus.orig[minus_first].begin;
 635                minus_end =
 636                        diff_words->minus.orig[minus_first + minus_len - 1].end;
 637        } else
 638                minus_begin = minus_end =
 639                        diff_words->minus.orig[minus_first].end;
 640
 641        if (plus_len) {
 642                plus_begin = diff_words->plus.orig[plus_first].begin;
 643                plus_end = diff_words->plus.orig[plus_first + plus_len - 1].end;
 644        } else
 645                plus_begin = plus_end = diff_words->plus.orig[plus_first].end;
 646
 647        if (diff_words->current_plus != plus_begin)
 648                fn_out_diff_words_write_helper(diff_words->file,
 649                                &style->ctx, style->newline,
 650                                plus_begin - diff_words->current_plus,
 651                                diff_words->current_plus);
 652        if (minus_begin != minus_end)
 653                fn_out_diff_words_write_helper(diff_words->file,
 654                                &style->old, style->newline,
 655                                minus_end - minus_begin, minus_begin);
 656        if (plus_begin != plus_end)
 657                fn_out_diff_words_write_helper(diff_words->file,
 658                                &style->new, style->newline,
 659                                plus_end - plus_begin, plus_begin);
 660
 661        diff_words->current_plus = plus_end;
 662}
 663
 664/* This function starts looking at *begin, and returns 0 iff a word was found. */
 665static int find_word_boundaries(mmfile_t *buffer, regex_t *word_regex,
 666                int *begin, int *end)
 667{
 668        if (word_regex && *begin < buffer->size) {
 669                regmatch_t match[1];
 670                if (!regexec(word_regex, buffer->ptr + *begin, 1, match, 0)) {
 671                        char *p = memchr(buffer->ptr + *begin + match[0].rm_so,
 672                                        '\n', match[0].rm_eo - match[0].rm_so);
 673                        *end = p ? p - buffer->ptr : match[0].rm_eo + *begin;
 674                        *begin += match[0].rm_so;
 675                        return *begin >= *end;
 676                }
 677                return -1;
 678        }
 679
 680        /* find the next word */
 681        while (*begin < buffer->size && isspace(buffer->ptr[*begin]))
 682                (*begin)++;
 683        if (*begin >= buffer->size)
 684                return -1;
 685
 686        /* find the end of the word */
 687        *end = *begin + 1;
 688        while (*end < buffer->size && !isspace(buffer->ptr[*end]))
 689                (*end)++;
 690
 691        return 0;
 692}
 693
 694/*
 695 * This function splits the words in buffer->text, stores the list with
 696 * newline separator into out, and saves the offsets of the original words
 697 * in buffer->orig.
 698 */
 699static void diff_words_fill(struct diff_words_buffer *buffer, mmfile_t *out,
 700                regex_t *word_regex)
 701{
 702        int i, j;
 703        long alloc = 0;
 704
 705        out->size = 0;
 706        out->ptr = NULL;
 707
 708        /* fake an empty "0th" word */
 709        ALLOC_GROW(buffer->orig, 1, buffer->orig_alloc);
 710        buffer->orig[0].begin = buffer->orig[0].end = buffer->text.ptr;
 711        buffer->orig_nr = 1;
 712
 713        for (i = 0; i < buffer->text.size; i++) {
 714                if (find_word_boundaries(&buffer->text, word_regex, &i, &j))
 715                        return;
 716
 717                /* store original boundaries */
 718                ALLOC_GROW(buffer->orig, buffer->orig_nr + 1,
 719                                buffer->orig_alloc);
 720                buffer->orig[buffer->orig_nr].begin = buffer->text.ptr + i;
 721                buffer->orig[buffer->orig_nr].end = buffer->text.ptr + j;
 722                buffer->orig_nr++;
 723
 724                /* store one word */
 725                ALLOC_GROW(out->ptr, out->size + j - i + 1, alloc);
 726                memcpy(out->ptr + out->size, buffer->text.ptr + i, j - i);
 727                out->ptr[out->size + j - i] = '\n';
 728                out->size += j - i + 1;
 729
 730                i = j - 1;
 731        }
 732}
 733
 734/* this executes the word diff on the accumulated buffers */
 735static void diff_words_show(struct diff_words_data *diff_words)
 736{
 737        xpparam_t xpp;
 738        xdemitconf_t xecfg;
 739        mmfile_t minus, plus;
 740        struct diff_words_style *style = diff_words->style;
 741
 742        /* special case: only removal */
 743        if (!diff_words->plus.text.size) {
 744                fn_out_diff_words_write_helper(diff_words->file,
 745                        &style->old, style->newline,
 746                        diff_words->minus.text.size, diff_words->minus.text.ptr);
 747                diff_words->minus.text.size = 0;
 748                return;
 749        }
 750
 751        diff_words->current_plus = diff_words->plus.text.ptr;
 752
 753        memset(&xpp, 0, sizeof(xpp));
 754        memset(&xecfg, 0, sizeof(xecfg));
 755        diff_words_fill(&diff_words->minus, &minus, diff_words->word_regex);
 756        diff_words_fill(&diff_words->plus, &plus, diff_words->word_regex);
 757        xpp.flags = 0;
 758        /* as only the hunk header will be parsed, we need a 0-context */
 759        xecfg.ctxlen = 0;
 760        xdi_diff_outf(&minus, &plus, fn_out_diff_words_aux, diff_words,
 761                      &xpp, &xecfg);
 762        free(minus.ptr);
 763        free(plus.ptr);
 764        if (diff_words->current_plus != diff_words->plus.text.ptr +
 765                        diff_words->plus.text.size)
 766                fn_out_diff_words_write_helper(diff_words->file,
 767                        &style->ctx, style->newline,
 768                        diff_words->plus.text.ptr + diff_words->plus.text.size
 769                        - diff_words->current_plus, diff_words->current_plus);
 770        diff_words->minus.text.size = diff_words->plus.text.size = 0;
 771}
 772
 773/* In "color-words" mode, show word-diff of words accumulated in the buffer */
 774static void diff_words_flush(struct emit_callback *ecbdata)
 775{
 776        if (ecbdata->diff_words->minus.text.size ||
 777            ecbdata->diff_words->plus.text.size)
 778                diff_words_show(ecbdata->diff_words);
 779}
 780
 781static void free_diff_words_data(struct emit_callback *ecbdata)
 782{
 783        if (ecbdata->diff_words) {
 784                diff_words_flush(ecbdata);
 785                free (ecbdata->diff_words->minus.text.ptr);
 786                free (ecbdata->diff_words->minus.orig);
 787                free (ecbdata->diff_words->plus.text.ptr);
 788                free (ecbdata->diff_words->plus.orig);
 789                free(ecbdata->diff_words->word_regex);
 790                free(ecbdata->diff_words);
 791                ecbdata->diff_words = NULL;
 792        }
 793}
 794
 795const char *diff_get_color(int diff_use_color, enum color_diff ix)
 796{
 797        if (diff_use_color)
 798                return diff_colors[ix];
 799        return "";
 800}
 801
 802static unsigned long sane_truncate_line(struct emit_callback *ecb, char *line, unsigned long len)
 803{
 804        const char *cp;
 805        unsigned long allot;
 806        size_t l = len;
 807
 808        if (ecb->truncate)
 809                return ecb->truncate(line, len);
 810        cp = line;
 811        allot = l;
 812        while (0 < l) {
 813                (void) utf8_width(&cp, &l);
 814                if (!cp)
 815                        break; /* truncated in the middle? */
 816        }
 817        return allot - l;
 818}
 819
 820static void find_lno(const char *line, struct emit_callback *ecbdata)
 821{
 822        const char *p;
 823        ecbdata->lno_in_preimage = 0;
 824        ecbdata->lno_in_postimage = 0;
 825        p = strchr(line, '-');
 826        if (!p)
 827                return; /* cannot happen */
 828        ecbdata->lno_in_preimage = strtol(p + 1, NULL, 10);
 829        p = strchr(p, '+');
 830        if (!p)
 831                return; /* cannot happen */
 832        ecbdata->lno_in_postimage = strtol(p + 1, NULL, 10);
 833}
 834
 835static void fn_out_consume(void *priv, char *line, unsigned long len)
 836{
 837        struct emit_callback *ecbdata = priv;
 838        const char *meta = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
 839        const char *plain = diff_get_color(ecbdata->color_diff, DIFF_PLAIN);
 840        const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
 841
 842        if (ecbdata->header) {
 843                fprintf(ecbdata->file, "%s", ecbdata->header->buf);
 844                strbuf_reset(ecbdata->header);
 845                ecbdata->header = NULL;
 846        }
 847        *(ecbdata->found_changesp) = 1;
 848
 849        if (ecbdata->label_path[0]) {
 850                const char *name_a_tab, *name_b_tab;
 851
 852                name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
 853                name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
 854
 855                fprintf(ecbdata->file, "%s--- %s%s%s\n",
 856                        meta, ecbdata->label_path[0], reset, name_a_tab);
 857                fprintf(ecbdata->file, "%s+++ %s%s%s\n",
 858                        meta, ecbdata->label_path[1], reset, name_b_tab);
 859                ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
 860        }
 861
 862        if (diff_suppress_blank_empty
 863            && len == 2 && line[0] == ' ' && line[1] == '\n') {
 864                line[0] = '\n';
 865                len = 1;
 866        }
 867
 868        if (line[0] == '@') {
 869                if (ecbdata->diff_words)
 870                        diff_words_flush(ecbdata);
 871                len = sane_truncate_line(ecbdata, line, len);
 872                find_lno(line, ecbdata);
 873                emit_hunk_header(ecbdata, line, len);
 874                if (line[len-1] != '\n')
 875                        putc('\n', ecbdata->file);
 876                return;
 877        }
 878
 879        if (len < 1) {
 880                emit_line(ecbdata->file, reset, reset, line, len);
 881                if (ecbdata->diff_words
 882                    && ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN)
 883                        fputs("~\n", ecbdata->file);
 884                return;
 885        }
 886
 887        if (ecbdata->diff_words) {
 888                if (line[0] == '-') {
 889                        diff_words_append(line, len,
 890                                          &ecbdata->diff_words->minus);
 891                        return;
 892                } else if (line[0] == '+') {
 893                        diff_words_append(line, len,
 894                                          &ecbdata->diff_words->plus);
 895                        return;
 896                }
 897                diff_words_flush(ecbdata);
 898                if (ecbdata->diff_words->type == DIFF_WORDS_PORCELAIN) {
 899                        emit_line(ecbdata->file, plain, reset, line, len);
 900                        fputs("~\n", ecbdata->file);
 901                } else {
 902                        /* don't print the prefix character */
 903                        emit_line(ecbdata->file, plain, reset, line+1, len-1);
 904                }
 905                return;
 906        }
 907
 908        if (line[0] != '+') {
 909                const char *color =
 910                        diff_get_color(ecbdata->color_diff,
 911                                       line[0] == '-' ? DIFF_FILE_OLD : DIFF_PLAIN);
 912                ecbdata->lno_in_preimage++;
 913                if (line[0] == ' ')
 914                        ecbdata->lno_in_postimage++;
 915                emit_line(ecbdata->file, color, reset, line, len);
 916        } else {
 917                ecbdata->lno_in_postimage++;
 918                emit_add_line(reset, ecbdata, line + 1, len - 1);
 919        }
 920}
 921
 922static char *pprint_rename(const char *a, const char *b)
 923{
 924        const char *old = a;
 925        const char *new = b;
 926        struct strbuf name = STRBUF_INIT;
 927        int pfx_length, sfx_length;
 928        int len_a = strlen(a);
 929        int len_b = strlen(b);
 930        int a_midlen, b_midlen;
 931        int qlen_a = quote_c_style(a, NULL, NULL, 0);
 932        int qlen_b = quote_c_style(b, NULL, NULL, 0);
 933
 934        if (qlen_a || qlen_b) {
 935                quote_c_style(a, &name, NULL, 0);
 936                strbuf_addstr(&name, " => ");
 937                quote_c_style(b, &name, NULL, 0);
 938                return strbuf_detach(&name, NULL);
 939        }
 940
 941        /* Find common prefix */
 942        pfx_length = 0;
 943        while (*old && *new && *old == *new) {
 944                if (*old == '/')
 945                        pfx_length = old - a + 1;
 946                old++;
 947                new++;
 948        }
 949
 950        /* Find common suffix */
 951        old = a + len_a;
 952        new = b + len_b;
 953        sfx_length = 0;
 954        while (a <= old && b <= new && *old == *new) {
 955                if (*old == '/')
 956                        sfx_length = len_a - (old - a);
 957                old--;
 958                new--;
 959        }
 960
 961        /*
 962         * pfx{mid-a => mid-b}sfx
 963         * {pfx-a => pfx-b}sfx
 964         * pfx{sfx-a => sfx-b}
 965         * name-a => name-b
 966         */
 967        a_midlen = len_a - pfx_length - sfx_length;
 968        b_midlen = len_b - pfx_length - sfx_length;
 969        if (a_midlen < 0)
 970                a_midlen = 0;
 971        if (b_midlen < 0)
 972                b_midlen = 0;
 973
 974        strbuf_grow(&name, pfx_length + a_midlen + b_midlen + sfx_length + 7);
 975        if (pfx_length + sfx_length) {
 976                strbuf_add(&name, a, pfx_length);
 977                strbuf_addch(&name, '{');
 978        }
 979        strbuf_add(&name, a + pfx_length, a_midlen);
 980        strbuf_addstr(&name, " => ");
 981        strbuf_add(&name, b + pfx_length, b_midlen);
 982        if (pfx_length + sfx_length) {
 983                strbuf_addch(&name, '}');
 984                strbuf_add(&name, a + len_a - sfx_length, sfx_length);
 985        }
 986        return strbuf_detach(&name, NULL);
 987}
 988
 989struct diffstat_t {
 990        int nr;
 991        int alloc;
 992        struct diffstat_file {
 993                char *from_name;
 994                char *name;
 995                char *print_name;
 996                unsigned is_unmerged:1;
 997                unsigned is_binary:1;
 998                unsigned is_renamed:1;
 999                uintmax_t added, deleted;
1000        } **files;
1001};
1002
1003static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
1004                                          const char *name_a,
1005                                          const char *name_b)
1006{
1007        struct diffstat_file *x;
1008        x = xcalloc(sizeof (*x), 1);
1009        if (diffstat->nr == diffstat->alloc) {
1010                diffstat->alloc = alloc_nr(diffstat->alloc);
1011                diffstat->files = xrealloc(diffstat->files,
1012                                diffstat->alloc * sizeof(x));
1013        }
1014        diffstat->files[diffstat->nr++] = x;
1015        if (name_b) {
1016                x->from_name = xstrdup(name_a);
1017                x->name = xstrdup(name_b);
1018                x->is_renamed = 1;
1019        }
1020        else {
1021                x->from_name = NULL;
1022                x->name = xstrdup(name_a);
1023        }
1024        return x;
1025}
1026
1027static void diffstat_consume(void *priv, char *line, unsigned long len)
1028{
1029        struct diffstat_t *diffstat = priv;
1030        struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
1031
1032        if (line[0] == '+')
1033                x->added++;
1034        else if (line[0] == '-')
1035                x->deleted++;
1036}
1037
1038const char mime_boundary_leader[] = "------------";
1039
1040static int scale_linear(int it, int width, int max_change)
1041{
1042        /*
1043         * make sure that at least one '-' is printed if there were deletions,
1044         * and likewise for '+'.
1045         */
1046        if (max_change < 2)
1047                return it;
1048        return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
1049}
1050
1051static void show_name(FILE *file,
1052                      const char *prefix, const char *name, int len)
1053{
1054        fprintf(file, " %s%-*s |", prefix, len, name);
1055}
1056
1057static void show_graph(FILE *file, char ch, int cnt, const char *set, const char *reset)
1058{
1059        if (cnt <= 0)
1060                return;
1061        fprintf(file, "%s", set);
1062        while (cnt--)
1063                putc(ch, file);
1064        fprintf(file, "%s", reset);
1065}
1066
1067static void fill_print_name(struct diffstat_file *file)
1068{
1069        char *pname;
1070
1071        if (file->print_name)
1072                return;
1073
1074        if (!file->is_renamed) {
1075                struct strbuf buf = STRBUF_INIT;
1076                if (quote_c_style(file->name, &buf, NULL, 0)) {
1077                        pname = strbuf_detach(&buf, NULL);
1078                } else {
1079                        pname = file->name;
1080                        strbuf_release(&buf);
1081                }
1082        } else {
1083                pname = pprint_rename(file->from_name, file->name);
1084        }
1085        file->print_name = pname;
1086}
1087
1088static void show_stats(struct diffstat_t *data, struct diff_options *options)
1089{
1090        int i, len, add, del, adds = 0, dels = 0;
1091        uintmax_t max_change = 0, max_len = 0;
1092        int total_files = data->nr;
1093        int width, name_width;
1094        const char *reset, *set, *add_c, *del_c;
1095
1096        if (data->nr == 0)
1097                return;
1098
1099        width = options->stat_width ? options->stat_width : 80;
1100        name_width = options->stat_name_width ? options->stat_name_width : 50;
1101
1102        /* Sanity: give at least 5 columns to the graph,
1103         * but leave at least 10 columns for the name.
1104         */
1105        if (width < 25)
1106                width = 25;
1107        if (name_width < 10)
1108                name_width = 10;
1109        else if (width < name_width + 15)
1110                name_width = width - 15;
1111
1112        /* Find the longest filename and max number of changes */
1113        reset = diff_get_color_opt(options, DIFF_RESET);
1114        set   = diff_get_color_opt(options, DIFF_PLAIN);
1115        add_c = diff_get_color_opt(options, DIFF_FILE_NEW);
1116        del_c = diff_get_color_opt(options, DIFF_FILE_OLD);
1117
1118        for (i = 0; i < data->nr; i++) {
1119                struct diffstat_file *file = data->files[i];
1120                uintmax_t change = file->added + file->deleted;
1121                fill_print_name(file);
1122                len = strlen(file->print_name);
1123                if (max_len < len)
1124                        max_len = len;
1125
1126                if (file->is_binary || file->is_unmerged)
1127                        continue;
1128                if (max_change < change)
1129                        max_change = change;
1130        }
1131
1132        /* Compute the width of the graph part;
1133         * 10 is for one blank at the beginning of the line plus
1134         * " | count " between the name and the graph.
1135         *
1136         * From here on, name_width is the width of the name area,
1137         * and width is the width of the graph area.
1138         */
1139        name_width = (name_width < max_len) ? name_width : max_len;
1140        if (width < (name_width + 10) + max_change)
1141                width = width - (name_width + 10);
1142        else
1143                width = max_change;
1144
1145        for (i = 0; i < data->nr; i++) {
1146                const char *prefix = "";
1147                char *name = data->files[i]->print_name;
1148                uintmax_t added = data->files[i]->added;
1149                uintmax_t deleted = data->files[i]->deleted;
1150                int name_len;
1151
1152                /*
1153                 * "scale" the filename
1154                 */
1155                len = name_width;
1156                name_len = strlen(name);
1157                if (name_width < name_len) {
1158                        char *slash;
1159                        prefix = "...";
1160                        len -= 3;
1161                        name += name_len - len;
1162                        slash = strchr(name, '/');
1163                        if (slash)
1164                                name = slash;
1165                }
1166
1167                if (data->files[i]->is_binary) {
1168                        show_name(options->file, prefix, name, len);
1169                        fprintf(options->file, "  Bin ");
1170                        fprintf(options->file, "%s%"PRIuMAX"%s",
1171                                del_c, deleted, reset);
1172                        fprintf(options->file, " -> ");
1173                        fprintf(options->file, "%s%"PRIuMAX"%s",
1174                                add_c, added, reset);
1175                        fprintf(options->file, " bytes");
1176                        fprintf(options->file, "\n");
1177                        continue;
1178                }
1179                else if (data->files[i]->is_unmerged) {
1180                        show_name(options->file, prefix, name, len);
1181                        fprintf(options->file, "  Unmerged\n");
1182                        continue;
1183                }
1184                else if (!data->files[i]->is_renamed &&
1185                         (added + deleted == 0)) {
1186                        total_files--;
1187                        continue;
1188                }
1189
1190                /*
1191                 * scale the add/delete
1192                 */
1193                add = added;
1194                del = deleted;
1195                adds += add;
1196                dels += del;
1197
1198                if (width <= max_change) {
1199                        add = scale_linear(add, width, max_change);
1200                        del = scale_linear(del, width, max_change);
1201                }
1202                show_name(options->file, prefix, name, len);
1203                fprintf(options->file, "%5"PRIuMAX"%s", added + deleted,
1204                                added + deleted ? " " : "");
1205                show_graph(options->file, '+', add, add_c, reset);
1206                show_graph(options->file, '-', del, del_c, reset);
1207                fprintf(options->file, "\n");
1208        }
1209        fprintf(options->file,
1210               " %d files changed, %d insertions(+), %d deletions(-)\n",
1211               total_files, adds, dels);
1212}
1213
1214static void show_shortstats(struct diffstat_t *data, struct diff_options *options)
1215{
1216        int i, adds = 0, dels = 0, total_files = data->nr;
1217
1218        if (data->nr == 0)
1219                return;
1220
1221        for (i = 0; i < data->nr; i++) {
1222                if (!data->files[i]->is_binary &&
1223                    !data->files[i]->is_unmerged) {
1224                        int added = data->files[i]->added;
1225                        int deleted= data->files[i]->deleted;
1226                        if (!data->files[i]->is_renamed &&
1227                            (added + deleted == 0)) {
1228                                total_files--;
1229                        } else {
1230                                adds += added;
1231                                dels += deleted;
1232                        }
1233                }
1234        }
1235        fprintf(options->file, " %d files changed, %d insertions(+), %d deletions(-)\n",
1236               total_files, adds, dels);
1237}
1238
1239static void show_numstat(struct diffstat_t *data, struct diff_options *options)
1240{
1241        int i;
1242
1243        if (data->nr == 0)
1244                return;
1245
1246        for (i = 0; i < data->nr; i++) {
1247                struct diffstat_file *file = data->files[i];
1248
1249                if (file->is_binary)
1250                        fprintf(options->file, "-\t-\t");
1251                else
1252                        fprintf(options->file,
1253                                "%"PRIuMAX"\t%"PRIuMAX"\t",
1254                                file->added, file->deleted);
1255                if (options->line_termination) {
1256                        fill_print_name(file);
1257                        if (!file->is_renamed)
1258                                write_name_quoted(file->name, options->file,
1259                                                  options->line_termination);
1260                        else {
1261                                fputs(file->print_name, options->file);
1262                                putc(options->line_termination, options->file);
1263                        }
1264                } else {
1265                        if (file->is_renamed) {
1266                                putc('\0', options->file);
1267                                write_name_quoted(file->from_name, options->file, '\0');
1268                        }
1269                        write_name_quoted(file->name, options->file, '\0');
1270                }
1271        }
1272}
1273
1274struct dirstat_file {
1275        const char *name;
1276        unsigned long changed;
1277};
1278
1279struct dirstat_dir {
1280        struct dirstat_file *files;
1281        int alloc, nr, percent, cumulative;
1282};
1283
1284static long gather_dirstat(FILE *file, struct dirstat_dir *dir, unsigned long changed, const char *base, int baselen)
1285{
1286        unsigned long this_dir = 0;
1287        unsigned int sources = 0;
1288
1289        while (dir->nr) {
1290                struct dirstat_file *f = dir->files;
1291                int namelen = strlen(f->name);
1292                unsigned long this;
1293                char *slash;
1294
1295                if (namelen < baselen)
1296                        break;
1297                if (memcmp(f->name, base, baselen))
1298                        break;
1299                slash = strchr(f->name + baselen, '/');
1300                if (slash) {
1301                        int newbaselen = slash + 1 - f->name;
1302                        this = gather_dirstat(file, dir, changed, f->name, newbaselen);
1303                        sources++;
1304                } else {
1305                        this = f->changed;
1306                        dir->files++;
1307                        dir->nr--;
1308                        sources += 2;
1309                }
1310                this_dir += this;
1311        }
1312
1313        /*
1314         * We don't report dirstat's for
1315         *  - the top level
1316         *  - or cases where everything came from a single directory
1317         *    under this directory (sources == 1).
1318         */
1319        if (baselen && sources != 1) {
1320                int permille = this_dir * 1000 / changed;
1321                if (permille) {
1322                        int percent = permille / 10;
1323                        if (percent >= dir->percent) {
1324                                fprintf(file, "%4d.%01d%% %.*s\n", percent, permille % 10, baselen, base);
1325                                if (!dir->cumulative)
1326                                        return 0;
1327                        }
1328                }
1329        }
1330        return this_dir;
1331}
1332
1333static int dirstat_compare(const void *_a, const void *_b)
1334{
1335        const struct dirstat_file *a = _a;
1336        const struct dirstat_file *b = _b;
1337        return strcmp(a->name, b->name);
1338}
1339
1340static void show_dirstat(struct diff_options *options)
1341{
1342        int i;
1343        unsigned long changed;
1344        struct dirstat_dir dir;
1345        struct diff_queue_struct *q = &diff_queued_diff;
1346
1347        dir.files = NULL;
1348        dir.alloc = 0;
1349        dir.nr = 0;
1350        dir.percent = options->dirstat_percent;
1351        dir.cumulative = DIFF_OPT_TST(options, DIRSTAT_CUMULATIVE);
1352
1353        changed = 0;
1354        for (i = 0; i < q->nr; i++) {
1355                struct diff_filepair *p = q->queue[i];
1356                const char *name;
1357                unsigned long copied, added, damage;
1358
1359                name = p->one->path ? p->one->path : p->two->path;
1360
1361                if (DIFF_FILE_VALID(p->one) && DIFF_FILE_VALID(p->two)) {
1362                        diff_populate_filespec(p->one, 0);
1363                        diff_populate_filespec(p->two, 0);
1364                        diffcore_count_changes(p->one, p->two, NULL, NULL, 0,
1365                                               &copied, &added);
1366                        diff_free_filespec_data(p->one);
1367                        diff_free_filespec_data(p->two);
1368                } else if (DIFF_FILE_VALID(p->one)) {
1369                        diff_populate_filespec(p->one, 1);
1370                        copied = added = 0;
1371                        diff_free_filespec_data(p->one);
1372                } else if (DIFF_FILE_VALID(p->two)) {
1373                        diff_populate_filespec(p->two, 1);
1374                        copied = 0;
1375                        added = p->two->size;
1376                        diff_free_filespec_data(p->two);
1377                } else
1378                        continue;
1379
1380                /*
1381                 * Original minus copied is the removed material,
1382                 * added is the new material.  They are both damages
1383                 * made to the preimage. In --dirstat-by-file mode, count
1384                 * damaged files, not damaged lines. This is done by
1385                 * counting only a single damaged line per file.
1386                 */
1387                damage = (p->one->size - copied) + added;
1388                if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0)
1389                        damage = 1;
1390
1391                ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc);
1392                dir.files[dir.nr].name = name;
1393                dir.files[dir.nr].changed = damage;
1394                changed += damage;
1395                dir.nr++;
1396        }
1397
1398        /* This can happen even with many files, if everything was renames */
1399        if (!changed)
1400                return;
1401
1402        /* Show all directories with more than x% of the changes */
1403        qsort(dir.files, dir.nr, sizeof(dir.files[0]), dirstat_compare);
1404        gather_dirstat(options->file, &dir, changed, "", 0);
1405}
1406
1407static void free_diffstat_info(struct diffstat_t *diffstat)
1408{
1409        int i;
1410        for (i = 0; i < diffstat->nr; i++) {
1411                struct diffstat_file *f = diffstat->files[i];
1412                if (f->name != f->print_name)
1413                        free(f->print_name);
1414                free(f->name);
1415                free(f->from_name);
1416                free(f);
1417        }
1418        free(diffstat->files);
1419}
1420
1421struct checkdiff_t {
1422        const char *filename;
1423        int lineno;
1424        int conflict_marker_size;
1425        struct diff_options *o;
1426        unsigned ws_rule;
1427        unsigned status;
1428};
1429
1430static int is_conflict_marker(const char *line, int marker_size, unsigned long len)
1431{
1432        char firstchar;
1433        int cnt;
1434
1435        if (len < marker_size + 1)
1436                return 0;
1437        firstchar = line[0];
1438        switch (firstchar) {
1439        case '=': case '>': case '<': case '|':
1440                break;
1441        default:
1442                return 0;
1443        }
1444        for (cnt = 1; cnt < marker_size; cnt++)
1445                if (line[cnt] != firstchar)
1446                        return 0;
1447        /* line[1] thru line[marker_size-1] are same as firstchar */
1448        if (len < marker_size + 1 || !isspace(line[marker_size]))
1449                return 0;
1450        return 1;
1451}
1452
1453static void checkdiff_consume(void *priv, char *line, unsigned long len)
1454{
1455        struct checkdiff_t *data = priv;
1456        int color_diff = DIFF_OPT_TST(data->o, COLOR_DIFF);
1457        int marker_size = data->conflict_marker_size;
1458        const char *ws = diff_get_color(color_diff, DIFF_WHITESPACE);
1459        const char *reset = diff_get_color(color_diff, DIFF_RESET);
1460        const char *set = diff_get_color(color_diff, DIFF_FILE_NEW);
1461        char *err;
1462
1463        if (line[0] == '+') {
1464                unsigned bad;
1465                data->lineno++;
1466                if (is_conflict_marker(line + 1, marker_size, len - 1)) {
1467                        data->status |= 1;
1468                        fprintf(data->o->file,
1469                                "%s:%d: leftover conflict marker\n",
1470                                data->filename, data->lineno);
1471                }
1472                bad = ws_check(line + 1, len - 1, data->ws_rule);
1473                if (!bad)
1474                        return;
1475                data->status |= bad;
1476                err = whitespace_error_string(bad);
1477                fprintf(data->o->file, "%s:%d: %s.\n",
1478                        data->filename, data->lineno, err);
1479                free(err);
1480                emit_line(data->o->file, set, reset, line, 1);
1481                ws_check_emit(line + 1, len - 1, data->ws_rule,
1482                              data->o->file, set, reset, ws);
1483        } else if (line[0] == ' ') {
1484                data->lineno++;
1485        } else if (line[0] == '@') {
1486                char *plus = strchr(line, '+');
1487                if (plus)
1488                        data->lineno = strtol(plus, NULL, 10) - 1;
1489                else
1490                        die("invalid diff");
1491        }
1492}
1493
1494static unsigned char *deflate_it(char *data,
1495                                 unsigned long size,
1496                                 unsigned long *result_size)
1497{
1498        int bound;
1499        unsigned char *deflated;
1500        z_stream stream;
1501
1502        memset(&stream, 0, sizeof(stream));
1503        deflateInit(&stream, zlib_compression_level);
1504        bound = deflateBound(&stream, size);
1505        deflated = xmalloc(bound);
1506        stream.next_out = deflated;
1507        stream.avail_out = bound;
1508
1509        stream.next_in = (unsigned char *)data;
1510        stream.avail_in = size;
1511        while (deflate(&stream, Z_FINISH) == Z_OK)
1512                ; /* nothing */
1513        deflateEnd(&stream);
1514        *result_size = stream.total_out;
1515        return deflated;
1516}
1517
1518static void emit_binary_diff_body(FILE *file, mmfile_t *one, mmfile_t *two)
1519{
1520        void *cp;
1521        void *delta;
1522        void *deflated;
1523        void *data;
1524        unsigned long orig_size;
1525        unsigned long delta_size;
1526        unsigned long deflate_size;
1527        unsigned long data_size;
1528
1529        /* We could do deflated delta, or we could do just deflated two,
1530         * whichever is smaller.
1531         */
1532        delta = NULL;
1533        deflated = deflate_it(two->ptr, two->size, &deflate_size);
1534        if (one->size && two->size) {
1535                delta = diff_delta(one->ptr, one->size,
1536                                   two->ptr, two->size,
1537                                   &delta_size, deflate_size);
1538                if (delta) {
1539                        void *to_free = delta;
1540                        orig_size = delta_size;
1541                        delta = deflate_it(delta, delta_size, &delta_size);
1542                        free(to_free);
1543                }
1544        }
1545
1546        if (delta && delta_size < deflate_size) {
1547                fprintf(file, "delta %lu\n", orig_size);
1548                free(deflated);
1549                data = delta;
1550                data_size = delta_size;
1551        }
1552        else {
1553                fprintf(file, "literal %lu\n", two->size);
1554                free(delta);
1555                data = deflated;
1556                data_size = deflate_size;
1557        }
1558
1559        /* emit data encoded in base85 */
1560        cp = data;
1561        while (data_size) {
1562                int bytes = (52 < data_size) ? 52 : data_size;
1563                char line[70];
1564                data_size -= bytes;
1565                if (bytes <= 26)
1566                        line[0] = bytes + 'A' - 1;
1567                else
1568                        line[0] = bytes - 26 + 'a' - 1;
1569                encode_85(line + 1, cp, bytes);
1570                cp = (char *) cp + bytes;
1571                fputs(line, file);
1572                fputc('\n', file);
1573        }
1574        fprintf(file, "\n");
1575        free(data);
1576}
1577
1578static void emit_binary_diff(FILE *file, mmfile_t *one, mmfile_t *two)
1579{
1580        fprintf(file, "GIT binary patch\n");
1581        emit_binary_diff_body(file, one, two);
1582        emit_binary_diff_body(file, two, one);
1583}
1584
1585static void diff_filespec_load_driver(struct diff_filespec *one)
1586{
1587        if (!one->driver)
1588                one->driver = userdiff_find_by_path(one->path);
1589        if (!one->driver)
1590                one->driver = userdiff_find_by_name("default");
1591}
1592
1593int diff_filespec_is_binary(struct diff_filespec *one)
1594{
1595        if (one->is_binary == -1) {
1596                diff_filespec_load_driver(one);
1597                if (one->driver->binary != -1)
1598                        one->is_binary = one->driver->binary;
1599                else {
1600                        if (!one->data && DIFF_FILE_VALID(one))
1601                                diff_populate_filespec(one, 0);
1602                        if (one->data)
1603                                one->is_binary = buffer_is_binary(one->data,
1604                                                one->size);
1605                        if (one->is_binary == -1)
1606                                one->is_binary = 0;
1607                }
1608        }
1609        return one->is_binary;
1610}
1611
1612static const struct userdiff_funcname *diff_funcname_pattern(struct diff_filespec *one)
1613{
1614        diff_filespec_load_driver(one);
1615        return one->driver->funcname.pattern ? &one->driver->funcname : NULL;
1616}
1617
1618static const char *userdiff_word_regex(struct diff_filespec *one)
1619{
1620        diff_filespec_load_driver(one);
1621        return one->driver->word_regex;
1622}
1623
1624void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b)
1625{
1626        if (!options->a_prefix)
1627                options->a_prefix = a;
1628        if (!options->b_prefix)
1629                options->b_prefix = b;
1630}
1631
1632static struct userdiff_driver *get_textconv(struct diff_filespec *one)
1633{
1634        if (!DIFF_FILE_VALID(one))
1635                return NULL;
1636        if (!S_ISREG(one->mode))
1637                return NULL;
1638        diff_filespec_load_driver(one);
1639        if (!one->driver->textconv)
1640                return NULL;
1641
1642        if (one->driver->textconv_want_cache && !one->driver->textconv_cache) {
1643                struct notes_cache *c = xmalloc(sizeof(*c));
1644                struct strbuf name = STRBUF_INIT;
1645
1646                strbuf_addf(&name, "textconv/%s", one->driver->name);
1647                notes_cache_init(c, name.buf, one->driver->textconv);
1648                one->driver->textconv_cache = c;
1649        }
1650
1651        return one->driver;
1652}
1653
1654static void builtin_diff(const char *name_a,
1655                         const char *name_b,
1656                         struct diff_filespec *one,
1657                         struct diff_filespec *two,
1658                         const char *xfrm_msg,
1659                         struct diff_options *o,
1660                         int complete_rewrite)
1661{
1662        mmfile_t mf1, mf2;
1663        const char *lbl[2];
1664        char *a_one, *b_two;
1665        const char *set = diff_get_color_opt(o, DIFF_METAINFO);
1666        const char *reset = diff_get_color_opt(o, DIFF_RESET);
1667        const char *a_prefix, *b_prefix;
1668        struct userdiff_driver *textconv_one = NULL;
1669        struct userdiff_driver *textconv_two = NULL;
1670        struct strbuf header = STRBUF_INIT;
1671
1672        if (DIFF_OPT_TST(o, SUBMODULE_LOG) &&
1673                        (!one->mode || S_ISGITLINK(one->mode)) &&
1674                        (!two->mode || S_ISGITLINK(two->mode))) {
1675                const char *del = diff_get_color_opt(o, DIFF_FILE_OLD);
1676                const char *add = diff_get_color_opt(o, DIFF_FILE_NEW);
1677                show_submodule_summary(o->file, one ? one->path : two->path,
1678                                one->sha1, two->sha1, two->dirty_submodule,
1679                                del, add, reset);
1680                return;
1681        }
1682
1683        if (DIFF_OPT_TST(o, ALLOW_TEXTCONV)) {
1684                textconv_one = get_textconv(one);
1685                textconv_two = get_textconv(two);
1686        }
1687
1688        diff_set_mnemonic_prefix(o, "a/", "b/");
1689        if (DIFF_OPT_TST(o, REVERSE_DIFF)) {
1690                a_prefix = o->b_prefix;
1691                b_prefix = o->a_prefix;
1692        } else {
1693                a_prefix = o->a_prefix;
1694                b_prefix = o->b_prefix;
1695        }
1696
1697        /* Never use a non-valid filename anywhere if at all possible */
1698        name_a = DIFF_FILE_VALID(one) ? name_a : name_b;
1699        name_b = DIFF_FILE_VALID(two) ? name_b : name_a;
1700
1701        a_one = quote_two(a_prefix, name_a + (*name_a == '/'));
1702        b_two = quote_two(b_prefix, name_b + (*name_b == '/'));
1703        lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1704        lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1705        strbuf_addf(&header, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1706        if (lbl[0][0] == '/') {
1707                /* /dev/null */
1708                strbuf_addf(&header, "%snew file mode %06o%s\n", set, two->mode, reset);
1709                if (xfrm_msg && xfrm_msg[0])
1710                        strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1711        }
1712        else if (lbl[1][0] == '/') {
1713                strbuf_addf(&header, "%sdeleted file mode %06o%s\n", set, one->mode, reset);
1714                if (xfrm_msg && xfrm_msg[0])
1715                        strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1716        }
1717        else {
1718                if (one->mode != two->mode) {
1719                        strbuf_addf(&header, "%sold mode %06o%s\n", set, one->mode, reset);
1720                        strbuf_addf(&header, "%snew mode %06o%s\n", set, two->mode, reset);
1721                }
1722                if (xfrm_msg && xfrm_msg[0])
1723                        strbuf_addf(&header, "%s%s%s\n", set, xfrm_msg, reset);
1724
1725                /*
1726                 * we do not run diff between different kind
1727                 * of objects.
1728                 */
1729                if ((one->mode ^ two->mode) & S_IFMT)
1730                        goto free_ab_and_return;
1731                if (complete_rewrite &&
1732                    (textconv_one || !diff_filespec_is_binary(one)) &&
1733                    (textconv_two || !diff_filespec_is_binary(two))) {
1734                        fprintf(o->file, "%s", header.buf);
1735                        strbuf_reset(&header);
1736                        emit_rewrite_diff(name_a, name_b, one, two,
1737                                                textconv_one, textconv_two, o);
1738                        o->found_changes = 1;
1739                        goto free_ab_and_return;
1740                }
1741        }
1742
1743        if (!DIFF_OPT_TST(o, TEXT) &&
1744            ( (!textconv_one && diff_filespec_is_binary(one)) ||
1745              (!textconv_two && diff_filespec_is_binary(two)) )) {
1746                if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1747                        die("unable to read files to diff");
1748                /* Quite common confusing case */
1749                if (mf1.size == mf2.size &&
1750                    !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1751                        goto free_ab_and_return;
1752                fprintf(o->file, "%s", header.buf);
1753                strbuf_reset(&header);
1754                if (DIFF_OPT_TST(o, BINARY))
1755                        emit_binary_diff(o->file, &mf1, &mf2);
1756                else
1757                        fprintf(o->file, "Binary files %s and %s differ\n",
1758                                lbl[0], lbl[1]);
1759                o->found_changes = 1;
1760        }
1761        else {
1762                /* Crazy xdl interfaces.. */
1763                const char *diffopts = getenv("GIT_DIFF_OPTS");
1764                xpparam_t xpp;
1765                xdemitconf_t xecfg;
1766                struct emit_callback ecbdata;
1767                const struct userdiff_funcname *pe;
1768
1769                if (!DIFF_XDL_TST(o, WHITESPACE_FLAGS)) {
1770                        fprintf(o->file, "%s", header.buf);
1771                        strbuf_reset(&header);
1772                }
1773
1774                mf1.size = fill_textconv(textconv_one, one, &mf1.ptr);
1775                mf2.size = fill_textconv(textconv_two, two, &mf2.ptr);
1776
1777                pe = diff_funcname_pattern(one);
1778                if (!pe)
1779                        pe = diff_funcname_pattern(two);
1780
1781                memset(&xpp, 0, sizeof(xpp));
1782                memset(&xecfg, 0, sizeof(xecfg));
1783                memset(&ecbdata, 0, sizeof(ecbdata));
1784                ecbdata.label_path = lbl;
1785                ecbdata.color_diff = DIFF_OPT_TST(o, COLOR_DIFF);
1786                ecbdata.found_changesp = &o->found_changes;
1787                ecbdata.ws_rule = whitespace_rule(name_b ? name_b : name_a);
1788                if (ecbdata.ws_rule & WS_BLANK_AT_EOF)
1789                        check_blank_at_eof(&mf1, &mf2, &ecbdata);
1790                ecbdata.file = o->file;
1791                ecbdata.header = header.len ? &header : NULL;
1792                xpp.flags = o->xdl_opts;
1793                xecfg.ctxlen = o->context;
1794                xecfg.interhunkctxlen = o->interhunkcontext;
1795                xecfg.flags = XDL_EMIT_FUNCNAMES;
1796                if (pe)
1797                        xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
1798                if (!diffopts)
1799                        ;
1800                else if (!prefixcmp(diffopts, "--unified="))
1801                        xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1802                else if (!prefixcmp(diffopts, "-u"))
1803                        xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1804                if (o->word_diff) {
1805                        int i;
1806
1807                        ecbdata.diff_words =
1808                                xcalloc(1, sizeof(struct diff_words_data));
1809                        ecbdata.diff_words->file = o->file;
1810                        ecbdata.diff_words->type = o->word_diff;
1811                        if (!o->word_regex)
1812                                o->word_regex = userdiff_word_regex(one);
1813                        if (!o->word_regex)
1814                                o->word_regex = userdiff_word_regex(two);
1815                        if (!o->word_regex)
1816                                o->word_regex = diff_word_regex_cfg;
1817                        if (o->word_regex) {
1818                                ecbdata.diff_words->word_regex = (regex_t *)
1819                                        xmalloc(sizeof(regex_t));
1820                                if (regcomp(ecbdata.diff_words->word_regex,
1821                                                o->word_regex,
1822                                                REG_EXTENDED | REG_NEWLINE))
1823                                        die ("Invalid regular expression: %s",
1824                                                        o->word_regex);
1825                        }
1826                        for (i = 0; i < ARRAY_SIZE(diff_words_styles); i++) {
1827                                if (o->word_diff == diff_words_styles[i].type) {
1828                                        ecbdata.diff_words->style =
1829                                                &diff_words_styles[i];
1830                                        break;
1831                                }
1832                        }
1833                        if (DIFF_OPT_TST(o, COLOR_DIFF)) {
1834                                struct diff_words_style *st = ecbdata.diff_words->style;
1835                                st->old.color = diff_get_color_opt(o, DIFF_FILE_OLD);
1836                                st->new.color = diff_get_color_opt(o, DIFF_FILE_NEW);
1837                                st->ctx.color = diff_get_color_opt(o, DIFF_PLAIN);
1838                        }
1839                }
1840                xdi_diff_outf(&mf1, &mf2, fn_out_consume, &ecbdata,
1841                              &xpp, &xecfg);
1842                if (o->word_diff)
1843                        free_diff_words_data(&ecbdata);
1844                if (textconv_one)
1845                        free(mf1.ptr);
1846                if (textconv_two)
1847                        free(mf2.ptr);
1848                xdiff_clear_find_func(&xecfg);
1849        }
1850
1851 free_ab_and_return:
1852        strbuf_release(&header);
1853        diff_free_filespec_data(one);
1854        diff_free_filespec_data(two);
1855        free(a_one);
1856        free(b_two);
1857        return;
1858}
1859
1860static void builtin_diffstat(const char *name_a, const char *name_b,
1861                             struct diff_filespec *one,
1862                             struct diff_filespec *two,
1863                             struct diffstat_t *diffstat,
1864                             struct diff_options *o,
1865                             int complete_rewrite)
1866{
1867        mmfile_t mf1, mf2;
1868        struct diffstat_file *data;
1869
1870        data = diffstat_add(diffstat, name_a, name_b);
1871
1872        if (!one || !two) {
1873                data->is_unmerged = 1;
1874                return;
1875        }
1876        if (complete_rewrite) {
1877                diff_populate_filespec(one, 0);
1878                diff_populate_filespec(two, 0);
1879                data->deleted = count_lines(one->data, one->size);
1880                data->added = count_lines(two->data, two->size);
1881                goto free_and_return;
1882        }
1883        if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1884                die("unable to read files to diff");
1885
1886        if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1887                data->is_binary = 1;
1888                data->added = mf2.size;
1889                data->deleted = mf1.size;
1890        } else {
1891                /* Crazy xdl interfaces.. */
1892                xpparam_t xpp;
1893                xdemitconf_t xecfg;
1894
1895                memset(&xpp, 0, sizeof(xpp));
1896                memset(&xecfg, 0, sizeof(xecfg));
1897                xpp.flags = o->xdl_opts;
1898                xdi_diff_outf(&mf1, &mf2, diffstat_consume, diffstat,
1899                              &xpp, &xecfg);
1900        }
1901
1902 free_and_return:
1903        diff_free_filespec_data(one);
1904        diff_free_filespec_data(two);
1905}
1906
1907static void builtin_checkdiff(const char *name_a, const char *name_b,
1908                              const char *attr_path,
1909                              struct diff_filespec *one,
1910                              struct diff_filespec *two,
1911                              struct diff_options *o)
1912{
1913        mmfile_t mf1, mf2;
1914        struct checkdiff_t data;
1915
1916        if (!two)
1917                return;
1918
1919        memset(&data, 0, sizeof(data));
1920        data.filename = name_b ? name_b : name_a;
1921        data.lineno = 0;
1922        data.o = o;
1923        data.ws_rule = whitespace_rule(attr_path);
1924        data.conflict_marker_size = ll_merge_marker_size(attr_path);
1925
1926        if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1927                die("unable to read files to diff");
1928
1929        /*
1930         * All the other codepaths check both sides, but not checking
1931         * the "old" side here is deliberate.  We are checking the newly
1932         * introduced changes, and as long as the "new" side is text, we
1933         * can and should check what it introduces.
1934         */
1935        if (diff_filespec_is_binary(two))
1936                goto free_and_return;
1937        else {
1938                /* Crazy xdl interfaces.. */
1939                xpparam_t xpp;
1940                xdemitconf_t xecfg;
1941
1942                memset(&xpp, 0, sizeof(xpp));
1943                memset(&xecfg, 0, sizeof(xecfg));
1944                xecfg.ctxlen = 1; /* at least one context line */
1945                xpp.flags = 0;
1946                xdi_diff_outf(&mf1, &mf2, checkdiff_consume, &data,
1947                              &xpp, &xecfg);
1948
1949                if (data.ws_rule & WS_BLANK_AT_EOF) {
1950                        struct emit_callback ecbdata;
1951                        int blank_at_eof;
1952
1953                        ecbdata.ws_rule = data.ws_rule;
1954                        check_blank_at_eof(&mf1, &mf2, &ecbdata);
1955                        blank_at_eof = ecbdata.blank_at_eof_in_preimage;
1956
1957                        if (blank_at_eof) {
1958                                static char *err;
1959                                if (!err)
1960                                        err = whitespace_error_string(WS_BLANK_AT_EOF);
1961                                fprintf(o->file, "%s:%d: %s.\n",
1962                                        data.filename, blank_at_eof, err);
1963                                data.status = 1; /* report errors */
1964                        }
1965                }
1966        }
1967 free_and_return:
1968        diff_free_filespec_data(one);
1969        diff_free_filespec_data(two);
1970        if (data.status)
1971                DIFF_OPT_SET(o, CHECK_FAILED);
1972}
1973
1974struct diff_filespec *alloc_filespec(const char *path)
1975{
1976        int namelen = strlen(path);
1977        struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1978
1979        memset(spec, 0, sizeof(*spec));
1980        spec->path = (char *)(spec + 1);
1981        memcpy(spec->path, path, namelen+1);
1982        spec->count = 1;
1983        spec->is_binary = -1;
1984        return spec;
1985}
1986
1987void free_filespec(struct diff_filespec *spec)
1988{
1989        if (!--spec->count) {
1990                diff_free_filespec_data(spec);
1991                free(spec);
1992        }
1993}
1994
1995void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1996                   unsigned short mode)
1997{
1998        if (mode) {
1999                spec->mode = canon_mode(mode);
2000                hashcpy(spec->sha1, sha1);
2001                spec->sha1_valid = !is_null_sha1(sha1);
2002        }
2003}
2004
2005/*
2006 * Given a name and sha1 pair, if the index tells us the file in
2007 * the work tree has that object contents, return true, so that
2008 * prepare_temp_file() does not have to inflate and extract.
2009 */
2010static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
2011{
2012        struct cache_entry *ce;
2013        struct stat st;
2014        int pos, len;
2015
2016        /*
2017         * We do not read the cache ourselves here, because the
2018         * benchmark with my previous version that always reads cache
2019         * shows that it makes things worse for diff-tree comparing
2020         * two linux-2.6 kernel trees in an already checked out work
2021         * tree.  This is because most diff-tree comparisons deal with
2022         * only a small number of files, while reading the cache is
2023         * expensive for a large project, and its cost outweighs the
2024         * savings we get by not inflating the object to a temporary
2025         * file.  Practically, this code only helps when we are used
2026         * by diff-cache --cached, which does read the cache before
2027         * calling us.
2028         */
2029        if (!active_cache)
2030                return 0;
2031
2032        /* We want to avoid the working directory if our caller
2033         * doesn't need the data in a normal file, this system
2034         * is rather slow with its stat/open/mmap/close syscalls,
2035         * and the object is contained in a pack file.  The pack
2036         * is probably already open and will be faster to obtain
2037         * the data through than the working directory.  Loose
2038         * objects however would tend to be slower as they need
2039         * to be individually opened and inflated.
2040         */
2041        if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1))
2042                return 0;
2043
2044        len = strlen(name);
2045        pos = cache_name_pos(name, len);
2046        if (pos < 0)
2047                return 0;
2048        ce = active_cache[pos];
2049
2050        /*
2051         * This is not the sha1 we are looking for, or
2052         * unreusable because it is not a regular file.
2053         */
2054        if (hashcmp(sha1, ce->sha1) || !S_ISREG(ce->ce_mode))
2055                return 0;
2056
2057        /*
2058         * If ce is marked as "assume unchanged", there is no
2059         * guarantee that work tree matches what we are looking for.
2060         */
2061        if ((ce->ce_flags & CE_VALID) || ce_skip_worktree(ce))
2062                return 0;
2063
2064        /*
2065         * If ce matches the file in the work tree, we can reuse it.
2066         */
2067        if (ce_uptodate(ce) ||
2068            (!lstat(name, &st) && !ce_match_stat(ce, &st, 0)))
2069                return 1;
2070
2071        return 0;
2072}
2073
2074static int populate_from_stdin(struct diff_filespec *s)
2075{
2076        struct strbuf buf = STRBUF_INIT;
2077        size_t size = 0;
2078
2079        if (strbuf_read(&buf, 0, 0) < 0)
2080                return error("error while reading from stdin %s",
2081                                     strerror(errno));
2082
2083        s->should_munmap = 0;
2084        s->data = strbuf_detach(&buf, &size);
2085        s->size = size;
2086        s->should_free = 1;
2087        return 0;
2088}
2089
2090static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
2091{
2092        int len;
2093        char *data = xmalloc(100), *dirty = "";
2094
2095        /* Are we looking at the work tree? */
2096        if (s->dirty_submodule)
2097                dirty = "-dirty";
2098
2099        len = snprintf(data, 100,
2100                       "Subproject commit %s%s\n", sha1_to_hex(s->sha1), dirty);
2101        s->data = data;
2102        s->size = len;
2103        s->should_free = 1;
2104        if (size_only) {
2105                s->data = NULL;
2106                free(data);
2107        }
2108        return 0;
2109}
2110
2111/*
2112 * While doing rename detection and pickaxe operation, we may need to
2113 * grab the data for the blob (or file) for our own in-core comparison.
2114 * diff_filespec has data and size fields for this purpose.
2115 */
2116int diff_populate_filespec(struct diff_filespec *s, int size_only)
2117{
2118        int err = 0;
2119        if (!DIFF_FILE_VALID(s))
2120                die("internal error: asking to populate invalid file.");
2121        if (S_ISDIR(s->mode))
2122                return -1;
2123
2124        if (s->data)
2125                return 0;
2126
2127        if (size_only && 0 < s->size)
2128                return 0;
2129
2130        if (S_ISGITLINK(s->mode))
2131                return diff_populate_gitlink(s, size_only);
2132
2133        if (!s->sha1_valid ||
2134            reuse_worktree_file(s->path, s->sha1, 0)) {
2135                struct strbuf buf = STRBUF_INIT;
2136                struct stat st;
2137                int fd;
2138
2139                if (!strcmp(s->path, "-"))
2140                        return populate_from_stdin(s);
2141
2142                if (lstat(s->path, &st) < 0) {
2143                        if (errno == ENOENT) {
2144                        err_empty:
2145                                err = -1;
2146                        empty:
2147                                s->data = (char *)"";
2148                                s->size = 0;
2149                                return err;
2150                        }
2151                }
2152                s->size = xsize_t(st.st_size);
2153                if (!s->size)
2154                        goto empty;
2155                if (S_ISLNK(st.st_mode)) {
2156                        struct strbuf sb = STRBUF_INIT;
2157
2158                        if (strbuf_readlink(&sb, s->path, s->size))
2159                                goto err_empty;
2160                        s->size = sb.len;
2161                        s->data = strbuf_detach(&sb, NULL);
2162                        s->should_free = 1;
2163                        return 0;
2164                }
2165                if (size_only)
2166                        return 0;
2167                fd = open(s->path, O_RDONLY);
2168                if (fd < 0)
2169                        goto err_empty;
2170                s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
2171                close(fd);
2172                s->should_munmap = 1;
2173
2174                /*
2175                 * Convert from working tree format to canonical git format
2176                 */
2177                if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) {
2178                        size_t size = 0;
2179                        munmap(s->data, s->size);
2180                        s->should_munmap = 0;
2181                        s->data = strbuf_detach(&buf, &size);
2182                        s->size = size;
2183                        s->should_free = 1;
2184                }
2185        }
2186        else {
2187                enum object_type type;
2188                if (size_only)
2189                        type = sha1_object_info(s->sha1, &s->size);
2190                else {
2191                        s->data = read_sha1_file(s->sha1, &type, &s->size);
2192                        s->should_free = 1;
2193                }
2194        }
2195        return 0;
2196}
2197
2198void diff_free_filespec_blob(struct diff_filespec *s)
2199{
2200        if (s->should_free)
2201                free(s->data);
2202        else if (s->should_munmap)
2203                munmap(s->data, s->size);
2204
2205        if (s->should_free || s->should_munmap) {
2206                s->should_free = s->should_munmap = 0;
2207                s->data = NULL;
2208        }
2209}
2210
2211void diff_free_filespec_data(struct diff_filespec *s)
2212{
2213        diff_free_filespec_blob(s);
2214        free(s->cnt_data);
2215        s->cnt_data = NULL;
2216}
2217
2218static void prep_temp_blob(const char *path, struct diff_tempfile *temp,
2219                           void *blob,
2220                           unsigned long size,
2221                           const unsigned char *sha1,
2222                           int mode)
2223{
2224        int fd;
2225        struct strbuf buf = STRBUF_INIT;
2226        struct strbuf template = STRBUF_INIT;
2227        char *path_dup = xstrdup(path);
2228        const char *base = basename(path_dup);
2229
2230        /* Generate "XXXXXX_basename.ext" */
2231        strbuf_addstr(&template, "XXXXXX_");
2232        strbuf_addstr(&template, base);
2233
2234        fd = git_mkstemps(temp->tmp_path, PATH_MAX, template.buf,
2235                        strlen(base) + 1);
2236        if (fd < 0)
2237                die_errno("unable to create temp-file");
2238        if (convert_to_working_tree(path,
2239                        (const char *)blob, (size_t)size, &buf)) {
2240                blob = buf.buf;
2241                size = buf.len;
2242        }
2243        if (write_in_full(fd, blob, size) != size)
2244                die_errno("unable to write temp-file");
2245        close(fd);
2246        temp->name = temp->tmp_path;
2247        strcpy(temp->hex, sha1_to_hex(sha1));
2248        temp->hex[40] = 0;
2249        sprintf(temp->mode, "%06o", mode);
2250        strbuf_release(&buf);
2251        strbuf_release(&template);
2252        free(path_dup);
2253}
2254
2255static struct diff_tempfile *prepare_temp_file(const char *name,
2256                struct diff_filespec *one)
2257{
2258        struct diff_tempfile *temp = claim_diff_tempfile();
2259
2260        if (!DIFF_FILE_VALID(one)) {
2261        not_a_valid_file:
2262                /* A '-' entry produces this for file-2, and
2263                 * a '+' entry produces this for file-1.
2264                 */
2265                temp->name = "/dev/null";
2266                strcpy(temp->hex, ".");
2267                strcpy(temp->mode, ".");
2268                return temp;
2269        }
2270
2271        if (!remove_tempfile_installed) {
2272                atexit(remove_tempfile);
2273                sigchain_push_common(remove_tempfile_on_signal);
2274                remove_tempfile_installed = 1;
2275        }
2276
2277        if (!one->sha1_valid ||
2278            reuse_worktree_file(name, one->sha1, 1)) {
2279                struct stat st;
2280                if (lstat(name, &st) < 0) {
2281                        if (errno == ENOENT)
2282                                goto not_a_valid_file;
2283                        die_errno("stat(%s)", name);
2284                }
2285                if (S_ISLNK(st.st_mode)) {
2286                        struct strbuf sb = STRBUF_INIT;
2287                        if (strbuf_readlink(&sb, name, st.st_size) < 0)
2288                                die_errno("readlink(%s)", name);
2289                        prep_temp_blob(name, temp, sb.buf, sb.len,
2290                                       (one->sha1_valid ?
2291                                        one->sha1 : null_sha1),
2292                                       (one->sha1_valid ?
2293                                        one->mode : S_IFLNK));
2294                        strbuf_release(&sb);
2295                }
2296                else {
2297                        /* we can borrow from the file in the work tree */
2298                        temp->name = name;
2299                        if (!one->sha1_valid)
2300                                strcpy(temp->hex, sha1_to_hex(null_sha1));
2301                        else
2302                                strcpy(temp->hex, sha1_to_hex(one->sha1));
2303                        /* Even though we may sometimes borrow the
2304                         * contents from the work tree, we always want
2305                         * one->mode.  mode is trustworthy even when
2306                         * !(one->sha1_valid), as long as
2307                         * DIFF_FILE_VALID(one).
2308                         */
2309                        sprintf(temp->mode, "%06o", one->mode);
2310                }
2311                return temp;
2312        }
2313        else {
2314                if (diff_populate_filespec(one, 0))
2315                        die("cannot read data blob for %s", one->path);
2316                prep_temp_blob(name, temp, one->data, one->size,
2317                               one->sha1, one->mode);
2318        }
2319        return temp;
2320}
2321
2322/* An external diff command takes:
2323 *
2324 * diff-cmd name infile1 infile1-sha1 infile1-mode \
2325 *               infile2 infile2-sha1 infile2-mode [ rename-to ]
2326 *
2327 */
2328static void run_external_diff(const char *pgm,
2329                              const char *name,
2330                              const char *other,
2331                              struct diff_filespec *one,
2332                              struct diff_filespec *two,
2333                              const char *xfrm_msg,
2334                              int complete_rewrite)
2335{
2336        const char *spawn_arg[10];
2337        int retval;
2338        const char **arg = &spawn_arg[0];
2339
2340        if (one && two) {
2341                struct diff_tempfile *temp_one, *temp_two;
2342                const char *othername = (other ? other : name);
2343                temp_one = prepare_temp_file(name, one);
2344                temp_two = prepare_temp_file(othername, two);
2345                *arg++ = pgm;
2346                *arg++ = name;
2347                *arg++ = temp_one->name;
2348                *arg++ = temp_one->hex;
2349                *arg++ = temp_one->mode;
2350                *arg++ = temp_two->name;
2351                *arg++ = temp_two->hex;
2352                *arg++ = temp_two->mode;
2353                if (other) {
2354                        *arg++ = other;
2355                        *arg++ = xfrm_msg;
2356                }
2357        } else {
2358                *arg++ = pgm;
2359                *arg++ = name;
2360        }
2361        *arg = NULL;
2362        fflush(NULL);
2363        retval = run_command_v_opt(spawn_arg, RUN_USING_SHELL);
2364        remove_tempfile();
2365        if (retval) {
2366                fprintf(stderr, "external diff died, stopping at %s.\n", name);
2367                exit(1);
2368        }
2369}
2370
2371static int similarity_index(struct diff_filepair *p)
2372{
2373        return p->score * 100 / MAX_SCORE;
2374}
2375
2376static void fill_metainfo(struct strbuf *msg,
2377                          const char *name,
2378                          const char *other,
2379                          struct diff_filespec *one,
2380                          struct diff_filespec *two,
2381                          struct diff_options *o,
2382                          struct diff_filepair *p)
2383{
2384        strbuf_init(msg, PATH_MAX * 2 + 300);
2385        switch (p->status) {
2386        case DIFF_STATUS_COPIED:
2387                strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2388                strbuf_addstr(msg, "\ncopy from ");
2389                quote_c_style(name, msg, NULL, 0);
2390                strbuf_addstr(msg, "\ncopy to ");
2391                quote_c_style(other, msg, NULL, 0);
2392                strbuf_addch(msg, '\n');
2393                break;
2394        case DIFF_STATUS_RENAMED:
2395                strbuf_addf(msg, "similarity index %d%%", similarity_index(p));
2396                strbuf_addstr(msg, "\nrename from ");
2397                quote_c_style(name, msg, NULL, 0);
2398                strbuf_addstr(msg, "\nrename to ");
2399                quote_c_style(other, msg, NULL, 0);
2400                strbuf_addch(msg, '\n');
2401                break;
2402        case DIFF_STATUS_MODIFIED:
2403                if (p->score) {
2404                        strbuf_addf(msg, "dissimilarity index %d%%\n",
2405                                    similarity_index(p));
2406                        break;
2407                }
2408                /* fallthru */
2409        default:
2410                /* nothing */
2411                ;
2412        }
2413        if (one && two && hashcmp(one->sha1, two->sha1)) {
2414                int abbrev = DIFF_OPT_TST(o, FULL_INDEX) ? 40 : DEFAULT_ABBREV;
2415
2416                if (DIFF_OPT_TST(o, BINARY)) {
2417                        mmfile_t mf;
2418                        if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
2419                            (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
2420                                abbrev = 40;
2421                }
2422                strbuf_addf(msg, "index %.*s..%.*s",
2423                            abbrev, sha1_to_hex(one->sha1),
2424                            abbrev, sha1_to_hex(two->sha1));
2425                if (one->mode == two->mode)
2426                        strbuf_addf(msg, " %06o", one->mode);
2427                strbuf_addch(msg, '\n');
2428        }
2429        if (msg->len)
2430                strbuf_setlen(msg, msg->len - 1);
2431}
2432
2433static void run_diff_cmd(const char *pgm,
2434                         const char *name,
2435                         const char *other,
2436                         const char *attr_path,
2437                         struct diff_filespec *one,
2438                         struct diff_filespec *two,
2439                         struct strbuf *msg,
2440                         struct diff_options *o,
2441                         struct diff_filepair *p)
2442{
2443        const char *xfrm_msg = NULL;
2444        int complete_rewrite = (p->status == DIFF_STATUS_MODIFIED) && p->score;
2445
2446        if (msg) {
2447                fill_metainfo(msg, name, other, one, two, o, p);
2448                xfrm_msg = msg->len ? msg->buf : NULL;
2449        }
2450
2451        if (!DIFF_OPT_TST(o, ALLOW_EXTERNAL))
2452                pgm = NULL;
2453        else {
2454                struct userdiff_driver *drv = userdiff_find_by_path(attr_path);
2455                if (drv && drv->external)
2456                        pgm = drv->external;
2457        }
2458
2459        if (pgm) {
2460                run_external_diff(pgm, name, other, one, two, xfrm_msg,
2461                                  complete_rewrite);
2462                return;
2463        }
2464        if (one && two)
2465                builtin_diff(name, other ? other : name,
2466                             one, two, xfrm_msg, o, complete_rewrite);
2467        else
2468                fprintf(o->file, "* Unmerged path %s\n", name);
2469}
2470
2471static void diff_fill_sha1_info(struct diff_filespec *one)
2472{
2473        if (DIFF_FILE_VALID(one)) {
2474                if (!one->sha1_valid) {
2475                        struct stat st;
2476                        if (!strcmp(one->path, "-")) {
2477                                hashcpy(one->sha1, null_sha1);
2478                                return;
2479                        }
2480                        if (lstat(one->path, &st) < 0)
2481                                die_errno("stat '%s'", one->path);
2482                        if (index_path(one->sha1, one->path, &st, 0))
2483                                die("cannot hash %s", one->path);
2484                }
2485        }
2486        else
2487                hashclr(one->sha1);
2488}
2489
2490static void strip_prefix(int prefix_length, const char **namep, const char **otherp)
2491{
2492        /* Strip the prefix but do not molest /dev/null and absolute paths */
2493        if (*namep && **namep != '/')
2494                *namep += prefix_length;
2495        if (*otherp && **otherp != '/')
2496                *otherp += prefix_length;
2497}
2498
2499static void run_diff(struct diff_filepair *p, struct diff_options *o)
2500{
2501        const char *pgm = external_diff();
2502        struct strbuf msg;
2503        struct diff_filespec *one = p->one;
2504        struct diff_filespec *two = p->two;
2505        const char *name;
2506        const char *other;
2507        const char *attr_path;
2508
2509        name  = p->one->path;
2510        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2511        attr_path = name;
2512        if (o->prefix_length)
2513                strip_prefix(o->prefix_length, &name, &other);
2514
2515        if (DIFF_PAIR_UNMERGED(p)) {
2516                run_diff_cmd(pgm, name, NULL, attr_path,
2517                             NULL, NULL, NULL, o, p);
2518                return;
2519        }
2520
2521        diff_fill_sha1_info(one);
2522        diff_fill_sha1_info(two);
2523
2524        if (!pgm &&
2525            DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
2526            (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
2527                /*
2528                 * a filepair that changes between file and symlink
2529                 * needs to be split into deletion and creation.
2530                 */
2531                struct diff_filespec *null = alloc_filespec(two->path);
2532                run_diff_cmd(NULL, name, other, attr_path,
2533                             one, null, &msg, o, p);
2534                free(null);
2535                strbuf_release(&msg);
2536
2537                null = alloc_filespec(one->path);
2538                run_diff_cmd(NULL, name, other, attr_path,
2539                             null, two, &msg, o, p);
2540                free(null);
2541        }
2542        else
2543                run_diff_cmd(pgm, name, other, attr_path,
2544                             one, two, &msg, o, p);
2545
2546        strbuf_release(&msg);
2547}
2548
2549static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
2550                         struct diffstat_t *diffstat)
2551{
2552        const char *name;
2553        const char *other;
2554        int complete_rewrite = 0;
2555
2556        if (DIFF_PAIR_UNMERGED(p)) {
2557                /* unmerged */
2558                builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
2559                return;
2560        }
2561
2562        name = p->one->path;
2563        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2564
2565        if (o->prefix_length)
2566                strip_prefix(o->prefix_length, &name, &other);
2567
2568        diff_fill_sha1_info(p->one);
2569        diff_fill_sha1_info(p->two);
2570
2571        if (p->status == DIFF_STATUS_MODIFIED && p->score)
2572                complete_rewrite = 1;
2573        builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
2574}
2575
2576static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
2577{
2578        const char *name;
2579        const char *other;
2580        const char *attr_path;
2581
2582        if (DIFF_PAIR_UNMERGED(p)) {
2583                /* unmerged */
2584                return;
2585        }
2586
2587        name = p->one->path;
2588        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
2589        attr_path = other ? other : name;
2590
2591        if (o->prefix_length)
2592                strip_prefix(o->prefix_length, &name, &other);
2593
2594        diff_fill_sha1_info(p->one);
2595        diff_fill_sha1_info(p->two);
2596
2597        builtin_checkdiff(name, other, attr_path, p->one, p->two, o);
2598}
2599
2600void diff_setup(struct diff_options *options)
2601{
2602        memset(options, 0, sizeof(*options));
2603        memset(&diff_queued_diff, 0, sizeof(diff_queued_diff));
2604
2605        options->file = stdout;
2606
2607        options->line_termination = '\n';
2608        options->break_opt = -1;
2609        options->rename_limit = -1;
2610        options->dirstat_percent = 3;
2611        options->context = 3;
2612
2613        options->change = diff_change;
2614        options->add_remove = diff_addremove;
2615        if (diff_use_color_default > 0)
2616                DIFF_OPT_SET(options, COLOR_DIFF);
2617        options->detect_rename = diff_detect_rename_default;
2618
2619        if (!diff_mnemonic_prefix) {
2620                options->a_prefix = "a/";
2621                options->b_prefix = "b/";
2622        }
2623}
2624
2625int diff_setup_done(struct diff_options *options)
2626{
2627        int count = 0;
2628
2629        if (options->output_format & DIFF_FORMAT_NAME)
2630                count++;
2631        if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2632                count++;
2633        if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2634                count++;
2635        if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2636                count++;
2637        if (count > 1)
2638                die("--name-only, --name-status, --check and -s are mutually exclusive");
2639
2640        /*
2641         * Most of the time we can say "there are changes"
2642         * only by checking if there are changed paths, but
2643         * --ignore-whitespace* options force us to look
2644         * inside contents.
2645         */
2646
2647        if (DIFF_XDL_TST(options, IGNORE_WHITESPACE) ||
2648            DIFF_XDL_TST(options, IGNORE_WHITESPACE_CHANGE) ||
2649            DIFF_XDL_TST(options, IGNORE_WHITESPACE_AT_EOL))
2650                DIFF_OPT_SET(options, DIFF_FROM_CONTENTS);
2651        else
2652                DIFF_OPT_CLR(options, DIFF_FROM_CONTENTS);
2653
2654        if (DIFF_OPT_TST(options, FIND_COPIES_HARDER))
2655                options->detect_rename = DIFF_DETECT_COPY;
2656
2657        if (!DIFF_OPT_TST(options, RELATIVE_NAME))
2658                options->prefix = NULL;
2659        if (options->prefix)
2660                options->prefix_length = strlen(options->prefix);
2661        else
2662                options->prefix_length = 0;
2663
2664        if (options->output_format & (DIFF_FORMAT_NAME |
2665                                      DIFF_FORMAT_NAME_STATUS |
2666                                      DIFF_FORMAT_CHECKDIFF |
2667                                      DIFF_FORMAT_NO_OUTPUT))
2668                options->output_format &= ~(DIFF_FORMAT_RAW |
2669                                            DIFF_FORMAT_NUMSTAT |
2670                                            DIFF_FORMAT_DIFFSTAT |
2671                                            DIFF_FORMAT_SHORTSTAT |
2672                                            DIFF_FORMAT_DIRSTAT |
2673                                            DIFF_FORMAT_SUMMARY |
2674                                            DIFF_FORMAT_PATCH);
2675
2676        /*
2677         * These cases always need recursive; we do not drop caller-supplied
2678         * recursive bits for other formats here.
2679         */
2680        if (options->output_format & (DIFF_FORMAT_PATCH |
2681                                      DIFF_FORMAT_NUMSTAT |
2682                                      DIFF_FORMAT_DIFFSTAT |
2683                                      DIFF_FORMAT_SHORTSTAT |
2684                                      DIFF_FORMAT_DIRSTAT |
2685                                      DIFF_FORMAT_SUMMARY |
2686                                      DIFF_FORMAT_CHECKDIFF))
2687                DIFF_OPT_SET(options, RECURSIVE);
2688        /*
2689         * Also pickaxe would not work very well if you do not say recursive
2690         */
2691        if (options->pickaxe)
2692                DIFF_OPT_SET(options, RECURSIVE);
2693        /*
2694         * When patches are generated, submodules diffed against the work tree
2695         * must be checked for dirtiness too so it can be shown in the output
2696         */
2697        if (options->output_format & DIFF_FORMAT_PATCH)
2698                DIFF_OPT_SET(options, DIRTY_SUBMODULES);
2699
2700        if (options->detect_rename && options->rename_limit < 0)
2701                options->rename_limit = diff_rename_limit_default;
2702        if (options->setup & DIFF_SETUP_USE_CACHE) {
2703                if (!active_cache)
2704                        /* read-cache does not die even when it fails
2705                         * so it is safe for us to do this here.  Also
2706                         * it does not smudge active_cache or active_nr
2707                         * when it fails, so we do not have to worry about
2708                         * cleaning it up ourselves either.
2709                         */
2710                        read_cache();
2711        }
2712        if (options->abbrev <= 0 || 40 < options->abbrev)
2713                options->abbrev = 40; /* full */
2714
2715        /*
2716         * It does not make sense to show the first hit we happened
2717         * to have found.  It does not make sense not to return with
2718         * exit code in such a case either.
2719         */
2720        if (DIFF_OPT_TST(options, QUICK)) {
2721                options->output_format = DIFF_FORMAT_NO_OUTPUT;
2722                DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2723        }
2724
2725        return 0;
2726}
2727
2728static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2729{
2730        char c, *eq;
2731        int len;
2732
2733        if (*arg != '-')
2734                return 0;
2735        c = *++arg;
2736        if (!c)
2737                return 0;
2738        if (c == arg_short) {
2739                c = *++arg;
2740                if (!c)
2741                        return 1;
2742                if (val && isdigit(c)) {
2743                        char *end;
2744                        int n = strtoul(arg, &end, 10);
2745                        if (*end)
2746                                return 0;
2747                        *val = n;
2748                        return 1;
2749                }
2750                return 0;
2751        }
2752        if (c != '-')
2753                return 0;
2754        arg++;
2755        eq = strchr(arg, '=');
2756        if (eq)
2757                len = eq - arg;
2758        else
2759                len = strlen(arg);
2760        if (!len || strncmp(arg, arg_long, len))
2761                return 0;
2762        if (eq) {
2763                int n;
2764                char *end;
2765                if (!isdigit(*++eq))
2766                        return 0;
2767                n = strtoul(eq, &end, 10);
2768                if (*end)
2769                        return 0;
2770                *val = n;
2771        }
2772        return 1;
2773}
2774
2775static int diff_scoreopt_parse(const char *opt);
2776
2777int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2778{
2779        const char *arg = av[0];
2780
2781        /* Output format options */
2782        if (!strcmp(arg, "-p") || !strcmp(arg, "-u") || !strcmp(arg, "--patch"))
2783                options->output_format |= DIFF_FORMAT_PATCH;
2784        else if (opt_arg(arg, 'U', "unified", &options->context))
2785                options->output_format |= DIFF_FORMAT_PATCH;
2786        else if (!strcmp(arg, "--raw"))
2787                options->output_format |= DIFF_FORMAT_RAW;
2788        else if (!strcmp(arg, "--patch-with-raw"))
2789                options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2790        else if (!strcmp(arg, "--numstat"))
2791                options->output_format |= DIFF_FORMAT_NUMSTAT;
2792        else if (!strcmp(arg, "--shortstat"))
2793                options->output_format |= DIFF_FORMAT_SHORTSTAT;
2794        else if (opt_arg(arg, 'X', "dirstat", &options->dirstat_percent))
2795                options->output_format |= DIFF_FORMAT_DIRSTAT;
2796        else if (!strcmp(arg, "--cumulative")) {
2797                options->output_format |= DIFF_FORMAT_DIRSTAT;
2798                DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE);
2799        } else if (opt_arg(arg, 0, "dirstat-by-file",
2800                           &options->dirstat_percent)) {
2801                options->output_format |= DIFF_FORMAT_DIRSTAT;
2802                DIFF_OPT_SET(options, DIRSTAT_BY_FILE);
2803        }
2804        else if (!strcmp(arg, "--check"))
2805                options->output_format |= DIFF_FORMAT_CHECKDIFF;
2806        else if (!strcmp(arg, "--summary"))
2807                options->output_format |= DIFF_FORMAT_SUMMARY;
2808        else if (!strcmp(arg, "--patch-with-stat"))
2809                options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2810        else if (!strcmp(arg, "--name-only"))
2811                options->output_format |= DIFF_FORMAT_NAME;
2812        else if (!strcmp(arg, "--name-status"))
2813                options->output_format |= DIFF_FORMAT_NAME_STATUS;
2814        else if (!strcmp(arg, "-s"))
2815                options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2816        else if (!prefixcmp(arg, "--stat")) {
2817                char *end;
2818                int width = options->stat_width;
2819                int name_width = options->stat_name_width;
2820                arg += 6;
2821                end = (char *)arg;
2822
2823                switch (*arg) {
2824                case '-':
2825                        if (!prefixcmp(arg, "-width="))
2826                                width = strtoul(arg + 7, &end, 10);
2827                        else if (!prefixcmp(arg, "-name-width="))
2828                                name_width = strtoul(arg + 12, &end, 10);
2829                        break;
2830                case '=':
2831                        width = strtoul(arg+1, &end, 10);
2832                        if (*end == ',')
2833                                name_width = strtoul(end+1, &end, 10);
2834                }
2835
2836                /* Important! This checks all the error cases! */
2837                if (*end)
2838                        return 0;
2839                options->output_format |= DIFF_FORMAT_DIFFSTAT;
2840                options->stat_name_width = name_width;
2841                options->stat_width = width;
2842        }
2843
2844        /* renames options */
2845        else if (!prefixcmp(arg, "-B")) {
2846                if ((options->break_opt = diff_scoreopt_parse(arg)) == -1)
2847                        return -1;
2848        }
2849        else if (!prefixcmp(arg, "-M")) {
2850                if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2851                        return -1;
2852                options->detect_rename = DIFF_DETECT_RENAME;
2853        }
2854        else if (!prefixcmp(arg, "-C")) {
2855                if (options->detect_rename == DIFF_DETECT_COPY)
2856                        DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2857                if ((options->rename_score = diff_scoreopt_parse(arg)) == -1)
2858                        return -1;
2859                options->detect_rename = DIFF_DETECT_COPY;
2860        }
2861        else if (!strcmp(arg, "--no-renames"))
2862                options->detect_rename = 0;
2863        else if (!strcmp(arg, "--relative"))
2864                DIFF_OPT_SET(options, RELATIVE_NAME);
2865        else if (!prefixcmp(arg, "--relative=")) {
2866                DIFF_OPT_SET(options, RELATIVE_NAME);
2867                options->prefix = arg + 11;
2868        }
2869
2870        /* xdiff options */
2871        else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2872                DIFF_XDL_SET(options, IGNORE_WHITESPACE);
2873        else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2874                DIFF_XDL_SET(options, IGNORE_WHITESPACE_CHANGE);
2875        else if (!strcmp(arg, "--ignore-space-at-eol"))
2876                DIFF_XDL_SET(options, IGNORE_WHITESPACE_AT_EOL);
2877        else if (!strcmp(arg, "--patience"))
2878                DIFF_XDL_SET(options, PATIENCE_DIFF);
2879
2880        /* flags options */
2881        else if (!strcmp(arg, "--binary")) {
2882                options->output_format |= DIFF_FORMAT_PATCH;
2883                DIFF_OPT_SET(options, BINARY);
2884        }
2885        else if (!strcmp(arg, "--full-index"))
2886                DIFF_OPT_SET(options, FULL_INDEX);
2887        else if (!strcmp(arg, "-a") || !strcmp(arg, "--text"))
2888                DIFF_OPT_SET(options, TEXT);
2889        else if (!strcmp(arg, "-R"))
2890                DIFF_OPT_SET(options, REVERSE_DIFF);
2891        else if (!strcmp(arg, "--find-copies-harder"))
2892                DIFF_OPT_SET(options, FIND_COPIES_HARDER);
2893        else if (!strcmp(arg, "--follow"))
2894                DIFF_OPT_SET(options, FOLLOW_RENAMES);
2895        else if (!strcmp(arg, "--color"))
2896                DIFF_OPT_SET(options, COLOR_DIFF);
2897        else if (!prefixcmp(arg, "--color=")) {
2898                int value = git_config_colorbool(NULL, arg+8, -1);
2899                if (value == 0)
2900                        DIFF_OPT_CLR(options, COLOR_DIFF);
2901                else if (value > 0)
2902                        DIFF_OPT_SET(options, COLOR_DIFF);
2903                else
2904                        return error("option `color' expects \"always\", \"auto\", or \"never\"");
2905        }
2906        else if (!strcmp(arg, "--no-color"))
2907                DIFF_OPT_CLR(options, COLOR_DIFF);
2908        else if (!strcmp(arg, "--color-words")) {
2909                DIFF_OPT_SET(options, COLOR_DIFF);
2910                options->word_diff = DIFF_WORDS_COLOR;
2911        }
2912        else if (!prefixcmp(arg, "--color-words=")) {
2913                DIFF_OPT_SET(options, COLOR_DIFF);
2914                options->word_diff = DIFF_WORDS_COLOR;
2915                options->word_regex = arg + 14;
2916        }
2917        else if (!strcmp(arg, "--word-diff")) {
2918                if (options->word_diff == DIFF_WORDS_NONE)
2919                        options->word_diff = DIFF_WORDS_PLAIN;
2920        }
2921        else if (!prefixcmp(arg, "--word-diff=")) {
2922                const char *type = arg + 12;
2923                if (!strcmp(type, "plain"))
2924                        options->word_diff = DIFF_WORDS_PLAIN;
2925                else if (!strcmp(type, "color")) {
2926                        DIFF_OPT_SET(options, COLOR_DIFF);
2927                        options->word_diff = DIFF_WORDS_COLOR;
2928                }
2929                else if (!strcmp(type, "porcelain"))
2930                        options->word_diff = DIFF_WORDS_PORCELAIN;
2931                else if (!strcmp(type, "none"))
2932                        options->word_diff = DIFF_WORDS_NONE;
2933                else
2934                        die("bad --word-diff argument: %s", type);
2935        }
2936        else if (!prefixcmp(arg, "--word-diff-regex=")) {
2937                if (options->word_diff == DIFF_WORDS_NONE)
2938                        options->word_diff = DIFF_WORDS_PLAIN;
2939                options->word_regex = arg + 18;
2940        }
2941        else if (!strcmp(arg, "--exit-code"))
2942                DIFF_OPT_SET(options, EXIT_WITH_STATUS);
2943        else if (!strcmp(arg, "--quiet"))
2944                DIFF_OPT_SET(options, QUICK);
2945        else if (!strcmp(arg, "--ext-diff"))
2946                DIFF_OPT_SET(options, ALLOW_EXTERNAL);
2947        else if (!strcmp(arg, "--no-ext-diff"))
2948                DIFF_OPT_CLR(options, ALLOW_EXTERNAL);
2949        else if (!strcmp(arg, "--textconv"))
2950                DIFF_OPT_SET(options, ALLOW_TEXTCONV);
2951        else if (!strcmp(arg, "--no-textconv"))
2952                DIFF_OPT_CLR(options, ALLOW_TEXTCONV);
2953        else if (!strcmp(arg, "--ignore-submodules"))
2954                DIFF_OPT_SET(options, IGNORE_SUBMODULES);
2955        else if (!strcmp(arg, "--submodule"))
2956                DIFF_OPT_SET(options, SUBMODULE_LOG);
2957        else if (!prefixcmp(arg, "--submodule=")) {
2958                if (!strcmp(arg + 12, "log"))
2959                        DIFF_OPT_SET(options, SUBMODULE_LOG);
2960        }
2961
2962        /* misc options */
2963        else if (!strcmp(arg, "-z"))
2964                options->line_termination = 0;
2965        else if (!prefixcmp(arg, "-l"))
2966                options->rename_limit = strtoul(arg+2, NULL, 10);
2967        else if (!prefixcmp(arg, "-S"))
2968                options->pickaxe = arg + 2;
2969        else if (!strcmp(arg, "--pickaxe-all"))
2970                options->pickaxe_opts = DIFF_PICKAXE_ALL;
2971        else if (!strcmp(arg, "--pickaxe-regex"))
2972                options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2973        else if (!prefixcmp(arg, "-O"))
2974                options->orderfile = arg + 2;
2975        else if (!prefixcmp(arg, "--diff-filter="))
2976                options->filter = arg + 14;
2977        else if (!strcmp(arg, "--abbrev"))
2978                options->abbrev = DEFAULT_ABBREV;
2979        else if (!prefixcmp(arg, "--abbrev=")) {
2980                options->abbrev = strtoul(arg + 9, NULL, 10);
2981                if (options->abbrev < MINIMUM_ABBREV)
2982                        options->abbrev = MINIMUM_ABBREV;
2983                else if (40 < options->abbrev)
2984                        options->abbrev = 40;
2985        }
2986        else if (!prefixcmp(arg, "--src-prefix="))
2987                options->a_prefix = arg + 13;
2988        else if (!prefixcmp(arg, "--dst-prefix="))
2989                options->b_prefix = arg + 13;
2990        else if (!strcmp(arg, "--no-prefix"))
2991                options->a_prefix = options->b_prefix = "";
2992        else if (opt_arg(arg, '\0', "inter-hunk-context",
2993                         &options->interhunkcontext))
2994                ;
2995        else if (!prefixcmp(arg, "--output=")) {
2996                options->file = fopen(arg + strlen("--output="), "w");
2997                if (!options->file)
2998                        die_errno("Could not open '%s'", arg + strlen("--output="));
2999                options->close_file = 1;
3000        } else
3001                return 0;
3002        return 1;
3003}
3004
3005static int parse_num(const char **cp_p)
3006{
3007        unsigned long num, scale;
3008        int ch, dot;
3009        const char *cp = *cp_p;
3010
3011        num = 0;
3012        scale = 1;
3013        dot = 0;
3014        for (;;) {
3015                ch = *cp;
3016                if ( !dot && ch == '.' ) {
3017                        scale = 1;
3018                        dot = 1;
3019                } else if ( ch == '%' ) {
3020                        scale = dot ? scale*100 : 100;
3021                        cp++;   /* % is always at the end */
3022                        break;
3023                } else if ( ch >= '0' && ch <= '9' ) {
3024                        if ( scale < 100000 ) {
3025                                scale *= 10;
3026                                num = (num*10) + (ch-'0');
3027                        }
3028                } else {
3029                        break;
3030                }
3031                cp++;
3032        }
3033        *cp_p = cp;
3034
3035        /* user says num divided by scale and we say internally that
3036         * is MAX_SCORE * num / scale.
3037         */
3038        return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
3039}
3040
3041static int diff_scoreopt_parse(const char *opt)
3042{
3043        int opt1, opt2, cmd;
3044
3045        if (*opt++ != '-')
3046                return -1;
3047        cmd = *opt++;
3048        if (cmd != 'M' && cmd != 'C' && cmd != 'B')
3049                return -1; /* that is not a -M, -C nor -B option */
3050
3051        opt1 = parse_num(&opt);
3052        if (cmd != 'B')
3053                opt2 = 0;
3054        else {
3055                if (*opt == 0)
3056                        opt2 = 0;
3057                else if (*opt != '/')
3058                        return -1; /* we expect -B80/99 or -B80 */
3059                else {
3060                        opt++;
3061                        opt2 = parse_num(&opt);
3062                }
3063        }
3064        if (*opt != 0)
3065                return -1;
3066        return opt1 | (opt2 << 16);
3067}
3068
3069struct diff_queue_struct diff_queued_diff;
3070
3071void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
3072{
3073        if (queue->alloc <= queue->nr) {
3074                queue->alloc = alloc_nr(queue->alloc);
3075                queue->queue = xrealloc(queue->queue,
3076                                        sizeof(dp) * queue->alloc);
3077        }
3078        queue->queue[queue->nr++] = dp;
3079}
3080
3081struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
3082                                 struct diff_filespec *one,
3083                                 struct diff_filespec *two)
3084{
3085        struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
3086        dp->one = one;
3087        dp->two = two;
3088        if (queue)
3089                diff_q(queue, dp);
3090        return dp;
3091}
3092
3093void diff_free_filepair(struct diff_filepair *p)
3094{
3095        free_filespec(p->one);
3096        free_filespec(p->two);
3097        free(p);
3098}
3099
3100/* This is different from find_unique_abbrev() in that
3101 * it stuffs the result with dots for alignment.
3102 */
3103const char *diff_unique_abbrev(const unsigned char *sha1, int len)
3104{
3105        int abblen;
3106        const char *abbrev;
3107        if (len == 40)
3108                return sha1_to_hex(sha1);
3109
3110        abbrev = find_unique_abbrev(sha1, len);
3111        abblen = strlen(abbrev);
3112        if (abblen < 37) {
3113                static char hex[41];
3114                if (len < abblen && abblen <= len + 2)
3115                        sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
3116                else
3117                        sprintf(hex, "%s...", abbrev);
3118                return hex;
3119        }
3120        return sha1_to_hex(sha1);
3121}
3122
3123static void diff_flush_raw(struct diff_filepair *p, struct diff_options *opt)
3124{
3125        int line_termination = opt->line_termination;
3126        int inter_name_termination = line_termination ? '\t' : '\0';
3127
3128        if (!(opt->output_format & DIFF_FORMAT_NAME_STATUS)) {
3129                fprintf(opt->file, ":%06o %06o %s ", p->one->mode, p->two->mode,
3130                        diff_unique_abbrev(p->one->sha1, opt->abbrev));
3131                fprintf(opt->file, "%s ", diff_unique_abbrev(p->two->sha1, opt->abbrev));
3132        }
3133        if (p->score) {
3134                fprintf(opt->file, "%c%03d%c", p->status, similarity_index(p),
3135                        inter_name_termination);
3136        } else {
3137                fprintf(opt->file, "%c%c", p->status, inter_name_termination);
3138        }
3139
3140        if (p->status == DIFF_STATUS_COPIED ||
3141            p->status == DIFF_STATUS_RENAMED) {
3142                const char *name_a, *name_b;
3143                name_a = p->one->path;
3144                name_b = p->two->path;
3145                strip_prefix(opt->prefix_length, &name_a, &name_b);
3146                write_name_quoted(name_a, opt->file, inter_name_termination);
3147                write_name_quoted(name_b, opt->file, line_termination);
3148        } else {
3149                const char *name_a, *name_b;
3150                name_a = p->one->mode ? p->one->path : p->two->path;
3151                name_b = NULL;
3152                strip_prefix(opt->prefix_length, &name_a, &name_b);
3153                write_name_quoted(name_a, opt->file, line_termination);
3154        }
3155}
3156
3157int diff_unmodified_pair(struct diff_filepair *p)
3158{
3159        /* This function is written stricter than necessary to support
3160         * the currently implemented transformers, but the idea is to
3161         * let transformers to produce diff_filepairs any way they want,
3162         * and filter and clean them up here before producing the output.
3163         */
3164        struct diff_filespec *one = p->one, *two = p->two;
3165
3166        if (DIFF_PAIR_UNMERGED(p))
3167                return 0; /* unmerged is interesting */
3168
3169        /* deletion, addition, mode or type change
3170         * and rename are all interesting.
3171         */
3172        if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
3173            DIFF_PAIR_MODE_CHANGED(p) ||
3174            strcmp(one->path, two->path))
3175                return 0;
3176
3177        /* both are valid and point at the same path.  that is, we are
3178         * dealing with a change.
3179         */
3180        if (one->sha1_valid && two->sha1_valid &&
3181            !hashcmp(one->sha1, two->sha1) &&
3182            !one->dirty_submodule && !two->dirty_submodule)
3183                return 1; /* no change */
3184        if (!one->sha1_valid && !two->sha1_valid)
3185                return 1; /* both look at the same file on the filesystem. */
3186        return 0;
3187}
3188
3189static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
3190{
3191        if (diff_unmodified_pair(p))
3192                return;
3193
3194        if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3195            (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3196                return; /* no tree diffs in patch format */
3197
3198        run_diff(p, o);
3199}
3200
3201static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
3202                            struct diffstat_t *diffstat)
3203{
3204        if (diff_unmodified_pair(p))
3205                return;
3206
3207        if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3208            (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3209                return; /* no tree diffs in patch format */
3210
3211        run_diffstat(p, o, diffstat);
3212}
3213
3214static void diff_flush_checkdiff(struct diff_filepair *p,
3215                struct diff_options *o)
3216{
3217        if (diff_unmodified_pair(p))
3218                return;
3219
3220        if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3221            (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3222                return; /* no tree diffs in patch format */
3223
3224        run_checkdiff(p, o);
3225}
3226
3227int diff_queue_is_empty(void)
3228{
3229        struct diff_queue_struct *q = &diff_queued_diff;
3230        int i;
3231        for (i = 0; i < q->nr; i++)
3232                if (!diff_unmodified_pair(q->queue[i]))
3233                        return 0;
3234        return 1;
3235}
3236
3237#if DIFF_DEBUG
3238void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
3239{
3240        fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
3241                x, one ? one : "",
3242                s->path,
3243                DIFF_FILE_VALID(s) ? "valid" : "invalid",
3244                s->mode,
3245                s->sha1_valid ? sha1_to_hex(s->sha1) : "");
3246        fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
3247                x, one ? one : "",
3248                s->size, s->xfrm_flags);
3249}
3250
3251void diff_debug_filepair(const struct diff_filepair *p, int i)
3252{
3253        diff_debug_filespec(p->one, i, "one");
3254        diff_debug_filespec(p->two, i, "two");
3255        fprintf(stderr, "score %d, status %c rename_used %d broken %d\n",
3256                p->score, p->status ? p->status : '?',
3257                p->one->rename_used, p->broken_pair);
3258}
3259
3260void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
3261{
3262        int i;
3263        if (msg)
3264                fprintf(stderr, "%s\n", msg);
3265        fprintf(stderr, "q->nr = %d\n", q->nr);
3266        for (i = 0; i < q->nr; i++) {
3267                struct diff_filepair *p = q->queue[i];
3268                diff_debug_filepair(p, i);
3269        }
3270}
3271#endif
3272
3273static void diff_resolve_rename_copy(void)
3274{
3275        int i;
3276        struct diff_filepair *p;
3277        struct diff_queue_struct *q = &diff_queued_diff;
3278
3279        diff_debug_queue("resolve-rename-copy", q);
3280
3281        for (i = 0; i < q->nr; i++) {
3282                p = q->queue[i];
3283                p->status = 0; /* undecided */
3284                if (DIFF_PAIR_UNMERGED(p))
3285                        p->status = DIFF_STATUS_UNMERGED;
3286                else if (!DIFF_FILE_VALID(p->one))
3287                        p->status = DIFF_STATUS_ADDED;
3288                else if (!DIFF_FILE_VALID(p->two))
3289                        p->status = DIFF_STATUS_DELETED;
3290                else if (DIFF_PAIR_TYPE_CHANGED(p))
3291                        p->status = DIFF_STATUS_TYPE_CHANGED;
3292
3293                /* from this point on, we are dealing with a pair
3294                 * whose both sides are valid and of the same type, i.e.
3295                 * either in-place edit or rename/copy edit.
3296                 */
3297                else if (DIFF_PAIR_RENAME(p)) {
3298                        /*
3299                         * A rename might have re-connected a broken
3300                         * pair up, causing the pathnames to be the
3301                         * same again. If so, that's not a rename at
3302                         * all, just a modification..
3303                         *
3304                         * Otherwise, see if this source was used for
3305                         * multiple renames, in which case we decrement
3306                         * the count, and call it a copy.
3307                         */
3308                        if (!strcmp(p->one->path, p->two->path))
3309                                p->status = DIFF_STATUS_MODIFIED;
3310                        else if (--p->one->rename_used > 0)
3311                                p->status = DIFF_STATUS_COPIED;
3312                        else
3313                                p->status = DIFF_STATUS_RENAMED;
3314                }
3315                else if (hashcmp(p->one->sha1, p->two->sha1) ||
3316                         p->one->mode != p->two->mode ||
3317                         p->one->dirty_submodule ||
3318                         p->two->dirty_submodule ||
3319                         is_null_sha1(p->one->sha1))
3320                        p->status = DIFF_STATUS_MODIFIED;
3321                else {
3322                        /* This is a "no-change" entry and should not
3323                         * happen anymore, but prepare for broken callers.
3324                         */
3325                        error("feeding unmodified %s to diffcore",
3326                              p->one->path);
3327                        p->status = DIFF_STATUS_UNKNOWN;
3328                }
3329        }
3330        diff_debug_queue("resolve-rename-copy done", q);
3331}
3332
3333static int check_pair_status(struct diff_filepair *p)
3334{
3335        switch (p->status) {
3336        case DIFF_STATUS_UNKNOWN:
3337                return 0;
3338        case 0:
3339                die("internal error in diff-resolve-rename-copy");
3340        default:
3341                return 1;
3342        }
3343}
3344
3345static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
3346{
3347        int fmt = opt->output_format;
3348
3349        if (fmt & DIFF_FORMAT_CHECKDIFF)
3350                diff_flush_checkdiff(p, opt);
3351        else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
3352                diff_flush_raw(p, opt);
3353        else if (fmt & DIFF_FORMAT_NAME) {
3354                const char *name_a, *name_b;
3355                name_a = p->two->path;
3356                name_b = NULL;
3357                strip_prefix(opt->prefix_length, &name_a, &name_b);
3358                write_name_quoted(name_a, opt->file, opt->line_termination);
3359        }
3360}
3361
3362static void show_file_mode_name(FILE *file, const char *newdelete, struct diff_filespec *fs)
3363{
3364        if (fs->mode)
3365                fprintf(file, " %s mode %06o ", newdelete, fs->mode);
3366        else
3367                fprintf(file, " %s ", newdelete);
3368        write_name_quoted(fs->path, file, '\n');
3369}
3370
3371
3372static void show_mode_change(FILE *file, struct diff_filepair *p, int show_name)
3373{
3374        if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
3375                fprintf(file, " mode change %06o => %06o%c", p->one->mode, p->two->mode,
3376                        show_name ? ' ' : '\n');
3377                if (show_name) {
3378                        write_name_quoted(p->two->path, file, '\n');
3379                }
3380        }
3381}
3382
3383static void show_rename_copy(FILE *file, const char *renamecopy, struct diff_filepair *p)
3384{
3385        char *names = pprint_rename(p->one->path, p->two->path);
3386
3387        fprintf(file, " %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
3388        free(names);
3389        show_mode_change(file, p, 0);
3390}
3391
3392static void diff_summary(FILE *file, struct diff_filepair *p)
3393{
3394        switch(p->status) {
3395        case DIFF_STATUS_DELETED:
3396                show_file_mode_name(file, "delete", p->one);
3397                break;
3398        case DIFF_STATUS_ADDED:
3399                show_file_mode_name(file, "create", p->two);
3400                break;
3401        case DIFF_STATUS_COPIED:
3402                show_rename_copy(file, "copy", p);
3403                break;
3404        case DIFF_STATUS_RENAMED:
3405                show_rename_copy(file, "rename", p);
3406                break;
3407        default:
3408                if (p->score) {
3409                        fputs(" rewrite ", file);
3410                        write_name_quoted(p->two->path, file, ' ');
3411                        fprintf(file, "(%d%%)\n", similarity_index(p));
3412                }
3413                show_mode_change(file, p, !p->score);
3414                break;
3415        }
3416}
3417
3418struct patch_id_t {
3419        git_SHA_CTX *ctx;
3420        int patchlen;
3421};
3422
3423static int remove_space(char *line, int len)
3424{
3425        int i;
3426        char *dst = line;
3427        unsigned char c;
3428
3429        for (i = 0; i < len; i++)
3430                if (!isspace((c = line[i])))
3431                        *dst++ = c;
3432
3433        return dst - line;
3434}
3435
3436static void patch_id_consume(void *priv, char *line, unsigned long len)
3437{
3438        struct patch_id_t *data = priv;
3439        int new_len;
3440
3441        /* Ignore line numbers when computing the SHA1 of the patch */
3442        if (!prefixcmp(line, "@@ -"))
3443                return;
3444
3445        new_len = remove_space(line, len);
3446
3447        git_SHA1_Update(data->ctx, line, new_len);
3448        data->patchlen += new_len;
3449}
3450
3451/* returns 0 upon success, and writes result into sha1 */
3452static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
3453{
3454        struct diff_queue_struct *q = &diff_queued_diff;
3455        int i;
3456        git_SHA_CTX ctx;
3457        struct patch_id_t data;
3458        char buffer[PATH_MAX * 4 + 20];
3459
3460        git_SHA1_Init(&ctx);
3461        memset(&data, 0, sizeof(struct patch_id_t));
3462        data.ctx = &ctx;
3463
3464        for (i = 0; i < q->nr; i++) {
3465                xpparam_t xpp;
3466                xdemitconf_t xecfg;
3467                mmfile_t mf1, mf2;
3468                struct diff_filepair *p = q->queue[i];
3469                int len1, len2;
3470
3471                memset(&xpp, 0, sizeof(xpp));
3472                memset(&xecfg, 0, sizeof(xecfg));
3473                if (p->status == 0)
3474                        return error("internal diff status error");
3475                if (p->status == DIFF_STATUS_UNKNOWN)
3476                        continue;
3477                if (diff_unmodified_pair(p))
3478                        continue;
3479                if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
3480                    (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
3481                        continue;
3482                if (DIFF_PAIR_UNMERGED(p))
3483                        continue;
3484
3485                diff_fill_sha1_info(p->one);
3486                diff_fill_sha1_info(p->two);
3487                if (fill_mmfile(&mf1, p->one) < 0 ||
3488                                fill_mmfile(&mf2, p->two) < 0)
3489                        return error("unable to read files to diff");
3490
3491                len1 = remove_space(p->one->path, strlen(p->one->path));
3492                len2 = remove_space(p->two->path, strlen(p->two->path));
3493                if (p->one->mode == 0)
3494                        len1 = snprintf(buffer, sizeof(buffer),
3495                                        "diff--gita/%.*sb/%.*s"
3496                                        "newfilemode%06o"
3497                                        "---/dev/null"
3498                                        "+++b/%.*s",
3499                                        len1, p->one->path,
3500                                        len2, p->two->path,
3501                                        p->two->mode,
3502                                        len2, p->two->path);
3503                else if (p->two->mode == 0)
3504                        len1 = snprintf(buffer, sizeof(buffer),
3505                                        "diff--gita/%.*sb/%.*s"
3506                                        "deletedfilemode%06o"
3507                                        "---a/%.*s"
3508                                        "+++/dev/null",
3509                                        len1, p->one->path,
3510                                        len2, p->two->path,
3511                                        p->one->mode,
3512                                        len1, p->one->path);
3513                else
3514                        len1 = snprintf(buffer, sizeof(buffer),
3515                                        "diff--gita/%.*sb/%.*s"
3516                                        "---a/%.*s"
3517                                        "+++b/%.*s",
3518                                        len1, p->one->path,
3519                                        len2, p->two->path,
3520                                        len1, p->one->path,
3521                                        len2, p->two->path);
3522                git_SHA1_Update(&ctx, buffer, len1);
3523
3524                xpp.flags = 0;
3525                xecfg.ctxlen = 3;
3526                xecfg.flags = XDL_EMIT_FUNCNAMES;
3527                xdi_diff_outf(&mf1, &mf2, patch_id_consume, &data,
3528                              &xpp, &xecfg);
3529        }
3530
3531        git_SHA1_Final(sha1, &ctx);
3532        return 0;
3533}
3534
3535int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
3536{
3537        struct diff_queue_struct *q = &diff_queued_diff;
3538        int i;
3539        int result = diff_get_patch_id(options, sha1);
3540
3541        for (i = 0; i < q->nr; i++)
3542                diff_free_filepair(q->queue[i]);
3543
3544        free(q->queue);
3545        DIFF_QUEUE_CLEAR(q);
3546
3547        return result;
3548}
3549
3550static int is_summary_empty(const struct diff_queue_struct *q)
3551{
3552        int i;
3553
3554        for (i = 0; i < q->nr; i++) {
3555                const struct diff_filepair *p = q->queue[i];
3556
3557                switch (p->status) {
3558                case DIFF_STATUS_DELETED:
3559                case DIFF_STATUS_ADDED:
3560                case DIFF_STATUS_COPIED:
3561                case DIFF_STATUS_RENAMED:
3562                        return 0;
3563                default:
3564                        if (p->score)
3565                                return 0;
3566                        if (p->one->mode && p->two->mode &&
3567                            p->one->mode != p->two->mode)
3568                                return 0;
3569                        break;
3570                }
3571        }
3572        return 1;
3573}
3574
3575void diff_flush(struct diff_options *options)
3576{
3577        struct diff_queue_struct *q = &diff_queued_diff;
3578        int i, output_format = options->output_format;
3579        int separator = 0;
3580
3581        /*
3582         * Order: raw, stat, summary, patch
3583         * or:    name/name-status/checkdiff (other bits clear)
3584         */
3585        if (!q->nr)
3586                goto free_queue;
3587
3588        if (output_format & (DIFF_FORMAT_RAW |
3589                             DIFF_FORMAT_NAME |
3590                             DIFF_FORMAT_NAME_STATUS |
3591                             DIFF_FORMAT_CHECKDIFF)) {
3592                for (i = 0; i < q->nr; i++) {
3593                        struct diff_filepair *p = q->queue[i];
3594                        if (check_pair_status(p))
3595                                flush_one_pair(p, options);
3596                }
3597                separator++;
3598        }
3599
3600        if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
3601                struct diffstat_t diffstat;
3602
3603                memset(&diffstat, 0, sizeof(struct diffstat_t));
3604                for (i = 0; i < q->nr; i++) {
3605                        struct diff_filepair *p = q->queue[i];
3606                        if (check_pair_status(p))
3607                                diff_flush_stat(p, options, &diffstat);
3608                }
3609                if (output_format & DIFF_FORMAT_NUMSTAT)
3610                        show_numstat(&diffstat, options);
3611                if (output_format & DIFF_FORMAT_DIFFSTAT)
3612                        show_stats(&diffstat, options);
3613                if (output_format & DIFF_FORMAT_SHORTSTAT)
3614                        show_shortstats(&diffstat, options);
3615                free_diffstat_info(&diffstat);
3616                separator++;
3617        }
3618        if (output_format & DIFF_FORMAT_DIRSTAT)
3619                show_dirstat(options);
3620
3621        if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
3622                for (i = 0; i < q->nr; i++)
3623                        diff_summary(options->file, q->queue[i]);
3624                separator++;
3625        }
3626
3627        if (output_format & DIFF_FORMAT_NO_OUTPUT &&
3628            DIFF_OPT_TST(options, EXIT_WITH_STATUS) &&
3629            DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3630                /*
3631                 * run diff_flush_patch for the exit status. setting
3632                 * options->file to /dev/null should be safe, becaue we
3633                 * aren't supposed to produce any output anyway.
3634                 */
3635                if (options->close_file)
3636                        fclose(options->file);
3637                options->file = fopen("/dev/null", "w");
3638                if (!options->file)
3639                        die_errno("Could not open /dev/null");
3640                options->close_file = 1;
3641                for (i = 0; i < q->nr; i++) {
3642                        struct diff_filepair *p = q->queue[i];
3643                        if (check_pair_status(p))
3644                                diff_flush_patch(p, options);
3645                        if (options->found_changes)
3646                                break;
3647                }
3648        }
3649
3650        if (output_format & DIFF_FORMAT_PATCH) {
3651                if (separator) {
3652                        putc(options->line_termination, options->file);
3653                        if (options->stat_sep) {
3654                                /* attach patch instead of inline */
3655                                fputs(options->stat_sep, options->file);
3656                        }
3657                }
3658
3659                for (i = 0; i < q->nr; i++) {
3660                        struct diff_filepair *p = q->queue[i];
3661                        if (check_pair_status(p))
3662                                diff_flush_patch(p, options);
3663                }
3664        }
3665
3666        if (output_format & DIFF_FORMAT_CALLBACK)
3667                options->format_callback(q, options, options->format_callback_data);
3668
3669        for (i = 0; i < q->nr; i++)
3670                diff_free_filepair(q->queue[i]);
3671free_queue:
3672        free(q->queue);
3673        DIFF_QUEUE_CLEAR(q);
3674        if (options->close_file)
3675                fclose(options->file);
3676
3677        /*
3678         * Report the content-level differences with HAS_CHANGES;
3679         * diff_addremove/diff_change does not set the bit when
3680         * DIFF_FROM_CONTENTS is in effect (e.g. with -w).
3681         */
3682        if (DIFF_OPT_TST(options, DIFF_FROM_CONTENTS)) {
3683                if (options->found_changes)
3684                        DIFF_OPT_SET(options, HAS_CHANGES);
3685                else
3686                        DIFF_OPT_CLR(options, HAS_CHANGES);
3687        }
3688}
3689
3690static void diffcore_apply_filter(const char *filter)
3691{
3692        int i;
3693        struct diff_queue_struct *q = &diff_queued_diff;
3694        struct diff_queue_struct outq;
3695        DIFF_QUEUE_CLEAR(&outq);
3696
3697        if (!filter)
3698                return;
3699
3700        if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
3701                int found;
3702                for (i = found = 0; !found && i < q->nr; i++) {
3703                        struct diff_filepair *p = q->queue[i];
3704                        if (((p->status == DIFF_STATUS_MODIFIED) &&
3705                             ((p->score &&
3706                               strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3707                              (!p->score &&
3708                               strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3709                            ((p->status != DIFF_STATUS_MODIFIED) &&
3710                             strchr(filter, p->status)))
3711                                found++;
3712                }
3713                if (found)
3714                        return;
3715
3716                /* otherwise we will clear the whole queue
3717                 * by copying the empty outq at the end of this
3718                 * function, but first clear the current entries
3719                 * in the queue.
3720                 */
3721                for (i = 0; i < q->nr; i++)
3722                        diff_free_filepair(q->queue[i]);
3723        }
3724        else {
3725                /* Only the matching ones */
3726                for (i = 0; i < q->nr; i++) {
3727                        struct diff_filepair *p = q->queue[i];
3728
3729                        if (((p->status == DIFF_STATUS_MODIFIED) &&
3730                             ((p->score &&
3731                               strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3732                              (!p->score &&
3733                               strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3734                            ((p->status != DIFF_STATUS_MODIFIED) &&
3735                             strchr(filter, p->status)))
3736                                diff_q(&outq, p);
3737                        else
3738                                diff_free_filepair(p);
3739                }
3740        }
3741        free(q->queue);
3742        *q = outq;
3743}
3744
3745/* Check whether two filespecs with the same mode and size are identical */
3746static int diff_filespec_is_identical(struct diff_filespec *one,
3747                                      struct diff_filespec *two)
3748{
3749        if (S_ISGITLINK(one->mode))
3750                return 0;
3751        if (diff_populate_filespec(one, 0))
3752                return 0;
3753        if (diff_populate_filespec(two, 0))
3754                return 0;
3755        return !memcmp(one->data, two->data, one->size);
3756}
3757
3758static void diffcore_skip_stat_unmatch(struct diff_options *diffopt)
3759{
3760        int i;
3761        struct diff_queue_struct *q = &diff_queued_diff;
3762        struct diff_queue_struct outq;
3763        DIFF_QUEUE_CLEAR(&outq);
3764
3765        for (i = 0; i < q->nr; i++) {
3766                struct diff_filepair *p = q->queue[i];
3767
3768                /*
3769                 * 1. Entries that come from stat info dirtiness
3770                 *    always have both sides (iow, not create/delete),
3771                 *    one side of the object name is unknown, with
3772                 *    the same mode and size.  Keep the ones that
3773                 *    do not match these criteria.  They have real
3774                 *    differences.
3775                 *
3776                 * 2. At this point, the file is known to be modified,
3777                 *    with the same mode and size, and the object
3778                 *    name of one side is unknown.  Need to inspect
3779                 *    the identical contents.
3780                 */
3781                if (!DIFF_FILE_VALID(p->one) || /* (1) */
3782                    !DIFF_FILE_VALID(p->two) ||
3783                    (p->one->sha1_valid && p->two->sha1_valid) ||
3784                    (p->one->mode != p->two->mode) ||
3785                    diff_populate_filespec(p->one, 1) ||
3786                    diff_populate_filespec(p->two, 1) ||
3787                    (p->one->size != p->two->size) ||
3788                    !diff_filespec_is_identical(p->one, p->two)) /* (2) */
3789                        diff_q(&outq, p);
3790                else {
3791                        /*
3792                         * The caller can subtract 1 from skip_stat_unmatch
3793                         * to determine how many paths were dirty only
3794                         * due to stat info mismatch.
3795                         */
3796                        if (!DIFF_OPT_TST(diffopt, NO_INDEX))
3797                                diffopt->skip_stat_unmatch++;
3798                        diff_free_filepair(p);
3799                }
3800        }
3801        free(q->queue);
3802        *q = outq;
3803}
3804
3805static int diffnamecmp(const void *a_, const void *b_)
3806{
3807        const struct diff_filepair *a = *((const struct diff_filepair **)a_);
3808        const struct diff_filepair *b = *((const struct diff_filepair **)b_);
3809        const char *name_a, *name_b;
3810
3811        name_a = a->one ? a->one->path : a->two->path;
3812        name_b = b->one ? b->one->path : b->two->path;
3813        return strcmp(name_a, name_b);
3814}
3815
3816void diffcore_fix_diff_index(struct diff_options *options)
3817{
3818        struct diff_queue_struct *q = &diff_queued_diff;
3819        qsort(q->queue, q->nr, sizeof(q->queue[0]), diffnamecmp);
3820}
3821
3822void diffcore_std(struct diff_options *options)
3823{
3824        /* We never run this function more than one time, because the
3825         * rename/copy detection logic can only run once.
3826         */
3827        if (diff_queued_diff.run)
3828                return;
3829
3830        if (options->skip_stat_unmatch)
3831                diffcore_skip_stat_unmatch(options);
3832        if (options->break_opt != -1)
3833                diffcore_break(options->break_opt);
3834        if (options->detect_rename)
3835                diffcore_rename(options);
3836        if (options->break_opt != -1)
3837                diffcore_merge_broken();
3838        if (options->pickaxe)
3839                diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3840        if (options->orderfile)
3841                diffcore_order(options->orderfile);
3842        diff_resolve_rename_copy();
3843        diffcore_apply_filter(options->filter);
3844
3845        if (diff_queued_diff.nr && !DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3846                DIFF_OPT_SET(options, HAS_CHANGES);
3847        else
3848                DIFF_OPT_CLR(options, HAS_CHANGES);
3849
3850        diff_queued_diff.run = 1;
3851}
3852
3853int diff_result_code(struct diff_options *opt, int status)
3854{
3855        int result = 0;
3856        if (!DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3857            !(opt->output_format & DIFF_FORMAT_CHECKDIFF))
3858                return status;
3859        if (DIFF_OPT_TST(opt, EXIT_WITH_STATUS) &&
3860            DIFF_OPT_TST(opt, HAS_CHANGES))
3861                result |= 01;
3862        if ((opt->output_format & DIFF_FORMAT_CHECKDIFF) &&
3863            DIFF_OPT_TST(opt, CHECK_FAILED))
3864                result |= 02;
3865        return result;
3866}
3867
3868void diff_addremove(struct diff_options *options,
3869                    int addremove, unsigned mode,
3870                    const unsigned char *sha1,
3871                    const char *concatpath, unsigned dirty_submodule)
3872{
3873        struct diff_filespec *one, *two;
3874
3875        if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(mode))
3876                return;
3877
3878        /* This may look odd, but it is a preparation for
3879         * feeding "there are unchanged files which should
3880         * not produce diffs, but when you are doing copy
3881         * detection you would need them, so here they are"
3882         * entries to the diff-core.  They will be prefixed
3883         * with something like '=' or '*' (I haven't decided
3884         * which but should not make any difference).
3885         * Feeding the same new and old to diff_change()
3886         * also has the same effect.
3887         * Before the final output happens, they are pruned after
3888         * merged into rename/copy pairs as appropriate.
3889         */
3890        if (DIFF_OPT_TST(options, REVERSE_DIFF))
3891                addremove = (addremove == '+' ? '-' :
3892                             addremove == '-' ? '+' : addremove);
3893
3894        if (options->prefix &&
3895            strncmp(concatpath, options->prefix, options->prefix_length))
3896                return;
3897
3898        one = alloc_filespec(concatpath);
3899        two = alloc_filespec(concatpath);
3900
3901        if (addremove != '+')
3902                fill_filespec(one, sha1, mode);
3903        if (addremove != '-') {
3904                fill_filespec(two, sha1, mode);
3905                two->dirty_submodule = dirty_submodule;
3906        }
3907
3908        diff_queue(&diff_queued_diff, one, two);
3909        if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3910                DIFF_OPT_SET(options, HAS_CHANGES);
3911}
3912
3913void diff_change(struct diff_options *options,
3914                 unsigned old_mode, unsigned new_mode,
3915                 const unsigned char *old_sha1,
3916                 const unsigned char *new_sha1,
3917                 const char *concatpath,
3918                 unsigned old_dirty_submodule, unsigned new_dirty_submodule)
3919{
3920        struct diff_filespec *one, *two;
3921
3922        if (DIFF_OPT_TST(options, IGNORE_SUBMODULES) && S_ISGITLINK(old_mode)
3923                        && S_ISGITLINK(new_mode))
3924                return;
3925
3926        if (DIFF_OPT_TST(options, REVERSE_DIFF)) {
3927                unsigned tmp;
3928                const unsigned char *tmp_c;
3929                tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3930                tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3931                tmp = old_dirty_submodule; old_dirty_submodule = new_dirty_submodule;
3932                        new_dirty_submodule = tmp;
3933        }
3934
3935        if (options->prefix &&
3936            strncmp(concatpath, options->prefix, options->prefix_length))
3937                return;
3938
3939        one = alloc_filespec(concatpath);
3940        two = alloc_filespec(concatpath);
3941        fill_filespec(one, old_sha1, old_mode);
3942        fill_filespec(two, new_sha1, new_mode);
3943        one->dirty_submodule = old_dirty_submodule;
3944        two->dirty_submodule = new_dirty_submodule;
3945
3946        diff_queue(&diff_queued_diff, one, two);
3947        if (!DIFF_OPT_TST(options, DIFF_FROM_CONTENTS))
3948                DIFF_OPT_SET(options, HAS_CHANGES);
3949}
3950
3951void diff_unmerge(struct diff_options *options,
3952                  const char *path,
3953                  unsigned mode, const unsigned char *sha1)
3954{
3955        struct diff_filespec *one, *two;
3956
3957        if (options->prefix &&
3958            strncmp(path, options->prefix, options->prefix_length))
3959                return;
3960
3961        one = alloc_filespec(path);
3962        two = alloc_filespec(path);
3963        fill_filespec(one, sha1, mode);
3964        diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3965}
3966
3967static char *run_textconv(const char *pgm, struct diff_filespec *spec,
3968                size_t *outsize)
3969{
3970        struct diff_tempfile *temp;
3971        const char *argv[3];
3972        const char **arg = argv;
3973        struct child_process child;
3974        struct strbuf buf = STRBUF_INIT;
3975        int err = 0;
3976
3977        temp = prepare_temp_file(spec->path, spec);
3978        *arg++ = pgm;
3979        *arg++ = temp->name;
3980        *arg = NULL;
3981
3982        memset(&child, 0, sizeof(child));
3983        child.use_shell = 1;
3984        child.argv = argv;
3985        child.out = -1;
3986        if (start_command(&child)) {
3987                remove_tempfile();
3988                return NULL;
3989        }
3990
3991        if (strbuf_read(&buf, child.out, 0) < 0)
3992                err = error("error reading from textconv command '%s'", pgm);
3993        close(child.out);
3994
3995        if (finish_command(&child) || err) {
3996                strbuf_release(&buf);
3997                remove_tempfile();
3998                return NULL;
3999        }
4000        remove_tempfile();
4001
4002        return strbuf_detach(&buf, outsize);
4003}
4004
4005static size_t fill_textconv(struct userdiff_driver *driver,
4006                            struct diff_filespec *df,
4007                            char **outbuf)
4008{
4009        size_t size;
4010
4011        if (!driver || !driver->textconv) {
4012                if (!DIFF_FILE_VALID(df)) {
4013                        *outbuf = "";
4014                        return 0;
4015                }
4016                if (diff_populate_filespec(df, 0))
4017                        die("unable to read files to diff");
4018                *outbuf = df->data;
4019                return df->size;
4020        }
4021
4022        if (driver->textconv_cache) {
4023                *outbuf = notes_cache_get(driver->textconv_cache, df->sha1,
4024                                          &size);
4025                if (*outbuf)
4026                        return size;
4027        }
4028
4029        *outbuf = run_textconv(driver->textconv, df, &size);
4030        if (!*outbuf)
4031                die("unable to read files to diff");
4032
4033        if (driver->textconv_cache) {
4034                /* ignore errors, as we might be in a readonly repository */
4035                notes_cache_put(driver->textconv_cache, df->sha1, *outbuf,
4036                                size);
4037                /*
4038                 * we could save up changes and flush them all at the end,
4039                 * but we would need an extra call after all diffing is done.
4040                 * Since generating a cache entry is the slow path anyway,
4041                 * this extra overhead probably isn't a big deal.
4042                 */
4043                notes_cache_write(driver->textconv_cache);
4044        }
4045
4046        return size;
4047}