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