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