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