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