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