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