d10e848c792bba581d6bf3e30204a81204177983
   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
  13#ifdef NO_FAST_WORKING_DIRECTORY
  14#define FAST_WORKING_DIRECTORY 0
  15#else
  16#define FAST_WORKING_DIRECTORY 1
  17#endif
  18
  19static int diff_detect_rename_default;
  20static int diff_rename_limit_default = -1;
  21static int diff_use_color_default;
  22
  23static char diff_colors[][COLOR_MAXLEN] = {
  24        "\033[m",       /* reset */
  25        "",             /* PLAIN (normal) */
  26        "\033[1m",      /* METAINFO (bold) */
  27        "\033[36m",     /* FRAGINFO (cyan) */
  28        "\033[31m",     /* OLD (red) */
  29        "\033[32m",     /* NEW (green) */
  30        "\033[33m",     /* COMMIT (yellow) */
  31        "\033[41m",     /* WHITESPACE (red background) */
  32};
  33
  34static int parse_diff_color_slot(const char *var, int ofs)
  35{
  36        if (!strcasecmp(var+ofs, "plain"))
  37                return DIFF_PLAIN;
  38        if (!strcasecmp(var+ofs, "meta"))
  39                return DIFF_METAINFO;
  40        if (!strcasecmp(var+ofs, "frag"))
  41                return DIFF_FRAGINFO;
  42        if (!strcasecmp(var+ofs, "old"))
  43                return DIFF_FILE_OLD;
  44        if (!strcasecmp(var+ofs, "new"))
  45                return DIFF_FILE_NEW;
  46        if (!strcasecmp(var+ofs, "commit"))
  47                return DIFF_COMMIT;
  48        if (!strcasecmp(var+ofs, "whitespace"))
  49                return DIFF_WHITESPACE;
  50        die("bad config variable '%s'", var);
  51}
  52
  53static struct ll_diff_driver {
  54        const char *name;
  55        struct ll_diff_driver *next;
  56        char *cmd;
  57} *user_diff, **user_diff_tail;
  58
  59/*
  60 * Currently there is only "diff.<drivername>.command" variable;
  61 * because there are "diff.color.<slot>" variables, we are parsing
  62 * this in a bit convoluted way to allow low level diff driver
  63 * called "color".
  64 */
  65static int parse_lldiff_command(const char *var, const char *ep, const char *value)
  66{
  67        const char *name;
  68        int namelen;
  69        struct ll_diff_driver *drv;
  70
  71        name = var + 5;
  72        namelen = ep - name;
  73        for (drv = user_diff; drv; drv = drv->next)
  74                if (!strncmp(drv->name, name, namelen) && !drv->name[namelen])
  75                        break;
  76        if (!drv) {
  77                char *namebuf;
  78                drv = xcalloc(1, sizeof(struct ll_diff_driver));
  79                namebuf = xmalloc(namelen + 1);
  80                memcpy(namebuf, name, namelen);
  81                namebuf[namelen] = 0;
  82                drv->name = namebuf;
  83                drv->next = NULL;
  84                if (!user_diff_tail)
  85                        user_diff_tail = &user_diff;
  86                *user_diff_tail = drv;
  87                user_diff_tail = &(drv->next);
  88        }
  89
  90        if (!value)
  91                return error("%s: lacks value", var);
  92        drv->cmd = strdup(value);
  93        return 0;
  94}
  95
  96/*
  97 * These are to give UI layer defaults.
  98 * The core-level commands such as git-diff-files should
  99 * never be affected by the setting of diff.renames
 100 * the user happens to have in the configuration file.
 101 */
 102int git_diff_ui_config(const char *var, const char *value)
 103{
 104        if (!strcmp(var, "diff.renamelimit")) {
 105                diff_rename_limit_default = git_config_int(var, value);
 106                return 0;
 107        }
 108        if (!strcmp(var, "diff.color") || !strcmp(var, "color.diff")) {
 109                diff_use_color_default = git_config_colorbool(var, value);
 110                return 0;
 111        }
 112        if (!strcmp(var, "diff.renames")) {
 113                if (!value)
 114                        diff_detect_rename_default = DIFF_DETECT_RENAME;
 115                else if (!strcasecmp(value, "copies") ||
 116                         !strcasecmp(value, "copy"))
 117                        diff_detect_rename_default = DIFF_DETECT_COPY;
 118                else if (git_config_bool(var,value))
 119                        diff_detect_rename_default = DIFF_DETECT_RENAME;
 120                return 0;
 121        }
 122        if (!prefixcmp(var, "diff.")) {
 123                const char *ep = strrchr(var, '.');
 124
 125                if (ep != var + 4 && !strcmp(ep, ".command"))
 126                        return parse_lldiff_command(var, ep, value);
 127        }
 128        if (!prefixcmp(var, "diff.color.") || !prefixcmp(var, "color.diff.")) {
 129                int slot = parse_diff_color_slot(var, 11);
 130                color_parse(value, var, diff_colors[slot]);
 131                return 0;
 132        }
 133
 134        return git_default_config(var, value);
 135}
 136
 137static char *quote_one(const char *str)
 138{
 139        int needlen;
 140        char *xp;
 141
 142        if (!str)
 143                return NULL;
 144        needlen = quote_c_style(str, NULL, NULL, 0);
 145        if (!needlen)
 146                return xstrdup(str);
 147        xp = xmalloc(needlen + 1);
 148        quote_c_style(str, xp, NULL, 0);
 149        return xp;
 150}
 151
 152static char *quote_two(const char *one, const char *two)
 153{
 154        int need_one = quote_c_style(one, NULL, NULL, 1);
 155        int need_two = quote_c_style(two, NULL, NULL, 1);
 156        char *xp;
 157
 158        if (need_one + need_two) {
 159                if (!need_one) need_one = strlen(one);
 160                if (!need_two) need_one = strlen(two);
 161
 162                xp = xmalloc(need_one + need_two + 3);
 163                xp[0] = '"';
 164                quote_c_style(one, xp + 1, NULL, 1);
 165                quote_c_style(two, xp + need_one + 1, NULL, 1);
 166                strcpy(xp + need_one + need_two + 1, "\"");
 167                return xp;
 168        }
 169        need_one = strlen(one);
 170        need_two = strlen(two);
 171        xp = xmalloc(need_one + need_two + 1);
 172        strcpy(xp, one);
 173        strcpy(xp + need_one, two);
 174        return xp;
 175}
 176
 177static const char *external_diff(void)
 178{
 179        static const char *external_diff_cmd = NULL;
 180        static int done_preparing = 0;
 181
 182        if (done_preparing)
 183                return external_diff_cmd;
 184        external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
 185        done_preparing = 1;
 186        return external_diff_cmd;
 187}
 188
 189static struct diff_tempfile {
 190        const char *name; /* filename external diff should read from */
 191        char hex[41];
 192        char mode[10];
 193        char tmp_path[PATH_MAX];
 194} diff_temp[2];
 195
 196static int count_lines(const char *data, int size)
 197{
 198        int count, ch, completely_empty = 1, nl_just_seen = 0;
 199        count = 0;
 200        while (0 < size--) {
 201                ch = *data++;
 202                if (ch == '\n') {
 203                        count++;
 204                        nl_just_seen = 1;
 205                        completely_empty = 0;
 206                }
 207                else {
 208                        nl_just_seen = 0;
 209                        completely_empty = 0;
 210                }
 211        }
 212        if (completely_empty)
 213                return 0;
 214        if (!nl_just_seen)
 215                count++; /* no trailing newline */
 216        return count;
 217}
 218
 219static void print_line_count(int count)
 220{
 221        switch (count) {
 222        case 0:
 223                printf("0,0");
 224                break;
 225        case 1:
 226                printf("1");
 227                break;
 228        default:
 229                printf("1,%d", count);
 230                break;
 231        }
 232}
 233
 234static void copy_file(int prefix, const char *data, int size,
 235                const char *set, const char *reset)
 236{
 237        int ch, nl_just_seen = 1;
 238        while (0 < size--) {
 239                ch = *data++;
 240                if (nl_just_seen) {
 241                        fputs(set, stdout);
 242                        putchar(prefix);
 243                }
 244                if (ch == '\n') {
 245                        nl_just_seen = 1;
 246                        fputs(reset, stdout);
 247                } else
 248                        nl_just_seen = 0;
 249                putchar(ch);
 250        }
 251        if (!nl_just_seen)
 252                printf("%s\n\\ No newline at end of file\n", reset);
 253}
 254
 255static void emit_rewrite_diff(const char *name_a,
 256                              const char *name_b,
 257                              struct diff_filespec *one,
 258                              struct diff_filespec *two,
 259                              int color_diff)
 260{
 261        int lc_a, lc_b;
 262        const char *name_a_tab, *name_b_tab;
 263        const char *metainfo = diff_get_color(color_diff, DIFF_METAINFO);
 264        const char *fraginfo = diff_get_color(color_diff, DIFF_FRAGINFO);
 265        const char *old = diff_get_color(color_diff, DIFF_FILE_OLD);
 266        const char *new = diff_get_color(color_diff, DIFF_FILE_NEW);
 267        const char *reset = diff_get_color(color_diff, DIFF_RESET);
 268
 269        name_a += (*name_a == '/');
 270        name_b += (*name_b == '/');
 271        name_a_tab = strchr(name_a, ' ') ? "\t" : "";
 272        name_b_tab = strchr(name_b, ' ') ? "\t" : "";
 273
 274        diff_populate_filespec(one, 0);
 275        diff_populate_filespec(two, 0);
 276        lc_a = count_lines(one->data, one->size);
 277        lc_b = count_lines(two->data, two->size);
 278        printf("%s--- a/%s%s%s\n%s+++ b/%s%s%s\n%s@@ -",
 279               metainfo, name_a, name_a_tab, reset,
 280               metainfo, name_b, name_b_tab, reset, fraginfo);
 281        print_line_count(lc_a);
 282        printf(" +");
 283        print_line_count(lc_b);
 284        printf(" @@%s\n", reset);
 285        if (lc_a)
 286                copy_file('-', one->data, one->size, old, reset);
 287        if (lc_b)
 288                copy_file('+', two->data, two->size, new, reset);
 289}
 290
 291static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
 292{
 293        if (!DIFF_FILE_VALID(one)) {
 294                mf->ptr = (char *)""; /* does not matter */
 295                mf->size = 0;
 296                return 0;
 297        }
 298        else if (diff_populate_filespec(one, 0))
 299                return -1;
 300        mf->ptr = one->data;
 301        mf->size = one->size;
 302        return 0;
 303}
 304
 305struct diff_words_buffer {
 306        mmfile_t text;
 307        long alloc;
 308        long current; /* output pointer */
 309        int suppressed_newline;
 310};
 311
 312static void diff_words_append(char *line, unsigned long len,
 313                struct diff_words_buffer *buffer)
 314{
 315        if (buffer->text.size + len > buffer->alloc) {
 316                buffer->alloc = (buffer->text.size + len) * 3 / 2;
 317                buffer->text.ptr = xrealloc(buffer->text.ptr, buffer->alloc);
 318        }
 319        line++;
 320        len--;
 321        memcpy(buffer->text.ptr + buffer->text.size, line, len);
 322        buffer->text.size += len;
 323}
 324
 325struct diff_words_data {
 326        struct xdiff_emit_state xm;
 327        struct diff_words_buffer minus, plus;
 328};
 329
 330static void print_word(struct diff_words_buffer *buffer, int len, int color,
 331                int suppress_newline)
 332{
 333        const char *ptr;
 334        int eol = 0;
 335
 336        if (len == 0)
 337                return;
 338
 339        ptr  = buffer->text.ptr + buffer->current;
 340        buffer->current += len;
 341
 342        if (ptr[len - 1] == '\n') {
 343                eol = 1;
 344                len--;
 345        }
 346
 347        fputs(diff_get_color(1, color), stdout);
 348        fwrite(ptr, len, 1, stdout);
 349        fputs(diff_get_color(1, DIFF_RESET), stdout);
 350
 351        if (eol) {
 352                if (suppress_newline)
 353                        buffer->suppressed_newline = 1;
 354                else
 355                        putchar('\n');
 356        }
 357}
 358
 359static void fn_out_diff_words_aux(void *priv, char *line, unsigned long len)
 360{
 361        struct diff_words_data *diff_words = priv;
 362
 363        if (diff_words->minus.suppressed_newline) {
 364                if (line[0] != '+')
 365                        putchar('\n');
 366                diff_words->minus.suppressed_newline = 0;
 367        }
 368
 369        len--;
 370        switch (line[0]) {
 371                case '-':
 372                        print_word(&diff_words->minus, len, DIFF_FILE_OLD, 1);
 373                        break;
 374                case '+':
 375                        print_word(&diff_words->plus, len, DIFF_FILE_NEW, 0);
 376                        break;
 377                case ' ':
 378                        print_word(&diff_words->plus, len, DIFF_PLAIN, 0);
 379                        diff_words->minus.current += len;
 380                        break;
 381        }
 382}
 383
 384/* this executes the word diff on the accumulated buffers */
 385static void diff_words_show(struct diff_words_data *diff_words)
 386{
 387        xpparam_t xpp;
 388        xdemitconf_t xecfg;
 389        xdemitcb_t ecb;
 390        mmfile_t minus, plus;
 391        int i;
 392
 393        memset(&xecfg, 0, sizeof(xecfg));
 394        minus.size = diff_words->minus.text.size;
 395        minus.ptr = xmalloc(minus.size);
 396        memcpy(minus.ptr, diff_words->minus.text.ptr, minus.size);
 397        for (i = 0; i < minus.size; i++)
 398                if (isspace(minus.ptr[i]))
 399                        minus.ptr[i] = '\n';
 400        diff_words->minus.current = 0;
 401
 402        plus.size = diff_words->plus.text.size;
 403        plus.ptr = xmalloc(plus.size);
 404        memcpy(plus.ptr, diff_words->plus.text.ptr, plus.size);
 405        for (i = 0; i < plus.size; i++)
 406                if (isspace(plus.ptr[i]))
 407                        plus.ptr[i] = '\n';
 408        diff_words->plus.current = 0;
 409
 410        xpp.flags = XDF_NEED_MINIMAL;
 411        xecfg.ctxlen = diff_words->minus.alloc + diff_words->plus.alloc;
 412        ecb.outf = xdiff_outf;
 413        ecb.priv = diff_words;
 414        diff_words->xm.consume = fn_out_diff_words_aux;
 415        xdl_diff(&minus, &plus, &xpp, &xecfg, &ecb);
 416
 417        free(minus.ptr);
 418        free(plus.ptr);
 419        diff_words->minus.text.size = diff_words->plus.text.size = 0;
 420
 421        if (diff_words->minus.suppressed_newline) {
 422                putchar('\n');
 423                diff_words->minus.suppressed_newline = 0;
 424        }
 425}
 426
 427struct emit_callback {
 428        struct xdiff_emit_state xm;
 429        int nparents, color_diff;
 430        const char **label_path;
 431        struct diff_words_data *diff_words;
 432        int *found_changesp;
 433};
 434
 435static void free_diff_words_data(struct emit_callback *ecbdata)
 436{
 437        if (ecbdata->diff_words) {
 438                /* flush buffers */
 439                if (ecbdata->diff_words->minus.text.size ||
 440                                ecbdata->diff_words->plus.text.size)
 441                        diff_words_show(ecbdata->diff_words);
 442
 443                if (ecbdata->diff_words->minus.text.ptr)
 444                        free (ecbdata->diff_words->minus.text.ptr);
 445                if (ecbdata->diff_words->plus.text.ptr)
 446                        free (ecbdata->diff_words->plus.text.ptr);
 447                free(ecbdata->diff_words);
 448                ecbdata->diff_words = NULL;
 449        }
 450}
 451
 452const char *diff_get_color(int diff_use_color, enum color_diff ix)
 453{
 454        if (diff_use_color)
 455                return diff_colors[ix];
 456        return "";
 457}
 458
 459static void emit_line(const char *set, const char *reset, const char *line, int len)
 460{
 461        if (len > 0 && line[len-1] == '\n')
 462                len--;
 463        fputs(set, stdout);
 464        fwrite(line, len, 1, stdout);
 465        puts(reset);
 466}
 467
 468static void emit_line_with_ws(int nparents,
 469                const char *set, const char *reset, const char *ws,
 470                const char *line, int len)
 471{
 472        int col0 = nparents;
 473        int last_tab_in_indent = -1;
 474        int last_space_in_indent = -1;
 475        int i;
 476        int tail = len;
 477        int need_highlight_leading_space = 0;
 478        /* The line is a newly added line.  Does it have funny leading
 479         * whitespaces?  In indent, SP should never precede a TAB.
 480         */
 481        for (i = col0; i < len; i++) {
 482                if (line[i] == '\t') {
 483                        last_tab_in_indent = i;
 484                        if (0 <= last_space_in_indent)
 485                                need_highlight_leading_space = 1;
 486                }
 487                else if (line[i] == ' ')
 488                        last_space_in_indent = i;
 489                else
 490                        break;
 491        }
 492        fputs(set, stdout);
 493        fwrite(line, col0, 1, stdout);
 494        fputs(reset, stdout);
 495        if (((i == len) || line[i] == '\n') && i != col0) {
 496                /* The whole line was indent */
 497                emit_line(ws, reset, line + col0, len - col0);
 498                return;
 499        }
 500        i = col0;
 501        if (need_highlight_leading_space) {
 502                while (i < last_tab_in_indent) {
 503                        if (line[i] == ' ') {
 504                                fputs(ws, stdout);
 505                                putchar(' ');
 506                                fputs(reset, stdout);
 507                        }
 508                        else
 509                                putchar(line[i]);
 510                        i++;
 511                }
 512        }
 513        tail = len - 1;
 514        if (line[tail] == '\n' && i < tail)
 515                tail--;
 516        while (i < tail) {
 517                if (!isspace(line[tail]))
 518                        break;
 519                tail--;
 520        }
 521        if ((i < tail && line[tail + 1] != '\n')) {
 522                /* This has whitespace between tail+1..len */
 523                fputs(set, stdout);
 524                fwrite(line + i, tail - i + 1, 1, stdout);
 525                fputs(reset, stdout);
 526                emit_line(ws, reset, line + tail + 1, len - tail - 1);
 527        }
 528        else
 529                emit_line(set, reset, line + i, len - i);
 530}
 531
 532static void emit_add_line(const char *reset, struct emit_callback *ecbdata, const char *line, int len)
 533{
 534        const char *ws = diff_get_color(ecbdata->color_diff, DIFF_WHITESPACE);
 535        const char *set = diff_get_color(ecbdata->color_diff, DIFF_FILE_NEW);
 536
 537        if (!*ws)
 538                emit_line(set, reset, line, len);
 539        else
 540                emit_line_with_ws(ecbdata->nparents, set, reset, ws,
 541                                line, len);
 542}
 543
 544static void fn_out_consume(void *priv, char *line, unsigned long len)
 545{
 546        int i;
 547        int color;
 548        struct emit_callback *ecbdata = priv;
 549        const char *set = diff_get_color(ecbdata->color_diff, DIFF_METAINFO);
 550        const char *reset = diff_get_color(ecbdata->color_diff, DIFF_RESET);
 551
 552        *(ecbdata->found_changesp) = 1;
 553
 554        if (ecbdata->label_path[0]) {
 555                const char *name_a_tab, *name_b_tab;
 556
 557                name_a_tab = strchr(ecbdata->label_path[0], ' ') ? "\t" : "";
 558                name_b_tab = strchr(ecbdata->label_path[1], ' ') ? "\t" : "";
 559
 560                printf("%s--- %s%s%s\n",
 561                       set, ecbdata->label_path[0], reset, name_a_tab);
 562                printf("%s+++ %s%s%s\n",
 563                       set, ecbdata->label_path[1], reset, name_b_tab);
 564                ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
 565        }
 566
 567        /* This is not really necessary for now because
 568         * this codepath only deals with two-way diffs.
 569         */
 570        for (i = 0; i < len && line[i] == '@'; i++)
 571                ;
 572        if (2 <= i && i < len && line[i] == ' ') {
 573                ecbdata->nparents = i - 1;
 574                emit_line(diff_get_color(ecbdata->color_diff, DIFF_FRAGINFO),
 575                          reset, line, len);
 576                return;
 577        }
 578
 579        if (len < ecbdata->nparents) {
 580                set = reset;
 581                emit_line(reset, reset, line, len);
 582                return;
 583        }
 584
 585        color = DIFF_PLAIN;
 586        if (ecbdata->diff_words && ecbdata->nparents != 1)
 587                /* fall back to normal diff */
 588                free_diff_words_data(ecbdata);
 589        if (ecbdata->diff_words) {
 590                if (line[0] == '-') {
 591                        diff_words_append(line, len,
 592                                          &ecbdata->diff_words->minus);
 593                        return;
 594                } else if (line[0] == '+') {
 595                        diff_words_append(line, len,
 596                                          &ecbdata->diff_words->plus);
 597                        return;
 598                }
 599                if (ecbdata->diff_words->minus.text.size ||
 600                    ecbdata->diff_words->plus.text.size)
 601                        diff_words_show(ecbdata->diff_words);
 602                line++;
 603                len--;
 604                emit_line(set, reset, line, len);
 605                return;
 606        }
 607        for (i = 0; i < ecbdata->nparents && len; i++) {
 608                if (line[i] == '-')
 609                        color = DIFF_FILE_OLD;
 610                else if (line[i] == '+')
 611                        color = DIFF_FILE_NEW;
 612        }
 613
 614        if (color != DIFF_FILE_NEW) {
 615                emit_line(diff_get_color(ecbdata->color_diff, color),
 616                          reset, line, len);
 617                return;
 618        }
 619        emit_add_line(reset, ecbdata, line, len);
 620}
 621
 622static char *pprint_rename(const char *a, const char *b)
 623{
 624        const char *old = a;
 625        const char *new = b;
 626        char *name = NULL;
 627        int pfx_length, sfx_length;
 628        int len_a = strlen(a);
 629        int len_b = strlen(b);
 630        int qlen_a = quote_c_style(a, NULL, NULL, 0);
 631        int qlen_b = quote_c_style(b, NULL, NULL, 0);
 632
 633        if (qlen_a || qlen_b) {
 634                if (qlen_a) len_a = qlen_a;
 635                if (qlen_b) len_b = qlen_b;
 636                name = xmalloc( len_a + len_b + 5 );
 637                if (qlen_a)
 638                        quote_c_style(a, name, NULL, 0);
 639                else
 640                        memcpy(name, a, len_a);
 641                memcpy(name + len_a, " => ", 4);
 642                if (qlen_b)
 643                        quote_c_style(b, name + len_a + 4, NULL, 0);
 644                else
 645                        memcpy(name + len_a + 4, b, len_b + 1);
 646                return name;
 647        }
 648
 649        /* Find common prefix */
 650        pfx_length = 0;
 651        while (*old && *new && *old == *new) {
 652                if (*old == '/')
 653                        pfx_length = old - a + 1;
 654                old++;
 655                new++;
 656        }
 657
 658        /* Find common suffix */
 659        old = a + len_a;
 660        new = b + len_b;
 661        sfx_length = 0;
 662        while (a <= old && b <= new && *old == *new) {
 663                if (*old == '/')
 664                        sfx_length = len_a - (old - a);
 665                old--;
 666                new--;
 667        }
 668
 669        /*
 670         * pfx{mid-a => mid-b}sfx
 671         * {pfx-a => pfx-b}sfx
 672         * pfx{sfx-a => sfx-b}
 673         * name-a => name-b
 674         */
 675        if (pfx_length + sfx_length) {
 676                int a_midlen = len_a - pfx_length - sfx_length;
 677                int b_midlen = len_b - pfx_length - sfx_length;
 678                if (a_midlen < 0) a_midlen = 0;
 679                if (b_midlen < 0) b_midlen = 0;
 680
 681                name = xmalloc(pfx_length + a_midlen + b_midlen + sfx_length + 7);
 682                sprintf(name, "%.*s{%.*s => %.*s}%s",
 683                        pfx_length, a,
 684                        a_midlen, a + pfx_length,
 685                        b_midlen, b + pfx_length,
 686                        a + len_a - sfx_length);
 687        }
 688        else {
 689                name = xmalloc(len_a + len_b + 5);
 690                sprintf(name, "%s => %s", a, b);
 691        }
 692        return name;
 693}
 694
 695struct diffstat_t {
 696        struct xdiff_emit_state xm;
 697
 698        int nr;
 699        int alloc;
 700        struct diffstat_file {
 701                char *name;
 702                unsigned is_unmerged:1;
 703                unsigned is_binary:1;
 704                unsigned is_renamed:1;
 705                unsigned int added, deleted;
 706        } **files;
 707};
 708
 709static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
 710                                          const char *name_a,
 711                                          const char *name_b)
 712{
 713        struct diffstat_file *x;
 714        x = xcalloc(sizeof (*x), 1);
 715        if (diffstat->nr == diffstat->alloc) {
 716                diffstat->alloc = alloc_nr(diffstat->alloc);
 717                diffstat->files = xrealloc(diffstat->files,
 718                                diffstat->alloc * sizeof(x));
 719        }
 720        diffstat->files[diffstat->nr++] = x;
 721        if (name_b) {
 722                x->name = pprint_rename(name_a, name_b);
 723                x->is_renamed = 1;
 724        }
 725        else
 726                x->name = xstrdup(name_a);
 727        return x;
 728}
 729
 730static void diffstat_consume(void *priv, char *line, unsigned long len)
 731{
 732        struct diffstat_t *diffstat = priv;
 733        struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
 734
 735        if (line[0] == '+')
 736                x->added++;
 737        else if (line[0] == '-')
 738                x->deleted++;
 739}
 740
 741const char mime_boundary_leader[] = "------------";
 742
 743static int scale_linear(int it, int width, int max_change)
 744{
 745        /*
 746         * make sure that at least one '-' is printed if there were deletions,
 747         * and likewise for '+'.
 748         */
 749        if (max_change < 2)
 750                return it;
 751        return ((it - 1) * (width - 1) + max_change - 1) / (max_change - 1);
 752}
 753
 754static void show_name(const char *prefix, const char *name, int len,
 755                      const char *reset, const char *set)
 756{
 757        printf(" %s%s%-*s%s |", set, prefix, len, name, reset);
 758}
 759
 760static void show_graph(char ch, int cnt, const char *set, const char *reset)
 761{
 762        if (cnt <= 0)
 763                return;
 764        printf("%s", set);
 765        while (cnt--)
 766                putchar(ch);
 767        printf("%s", reset);
 768}
 769
 770static void show_stats(struct diffstat_t* data, struct diff_options *options)
 771{
 772        int i, len, add, del, total, adds = 0, dels = 0;
 773        int max_change = 0, max_len = 0;
 774        int total_files = data->nr;
 775        int width, name_width;
 776        const char *reset, *set, *add_c, *del_c;
 777
 778        if (data->nr == 0)
 779                return;
 780
 781        width = options->stat_width ? options->stat_width : 80;
 782        name_width = options->stat_name_width ? options->stat_name_width : 50;
 783
 784        /* Sanity: give at least 5 columns to the graph,
 785         * but leave at least 10 columns for the name.
 786         */
 787        if (width < name_width + 15) {
 788                if (name_width <= 25)
 789                        width = name_width + 15;
 790                else
 791                        name_width = width - 15;
 792        }
 793
 794        /* Find the longest filename and max number of changes */
 795        reset = diff_get_color(options->color_diff, DIFF_RESET);
 796        set = diff_get_color(options->color_diff, DIFF_PLAIN);
 797        add_c = diff_get_color(options->color_diff, DIFF_FILE_NEW);
 798        del_c = diff_get_color(options->color_diff, DIFF_FILE_OLD);
 799
 800        for (i = 0; i < data->nr; i++) {
 801                struct diffstat_file *file = data->files[i];
 802                int change = file->added + file->deleted;
 803
 804                if (!file->is_renamed) {  /* renames are already quoted by pprint_rename */
 805                        len = quote_c_style(file->name, NULL, NULL, 0);
 806                        if (len) {
 807                                char *qname = xmalloc(len + 1);
 808                                quote_c_style(file->name, qname, NULL, 0);
 809                                free(file->name);
 810                                file->name = qname;
 811                        }
 812                }
 813
 814                len = strlen(file->name);
 815                if (max_len < len)
 816                        max_len = len;
 817
 818                if (file->is_binary || file->is_unmerged)
 819                        continue;
 820                if (max_change < change)
 821                        max_change = change;
 822        }
 823
 824        /* Compute the width of the graph part;
 825         * 10 is for one blank at the beginning of the line plus
 826         * " | count " between the name and the graph.
 827         *
 828         * From here on, name_width is the width of the name area,
 829         * and width is the width of the graph area.
 830         */
 831        name_width = (name_width < max_len) ? name_width : max_len;
 832        if (width < (name_width + 10) + max_change)
 833                width = width - (name_width + 10);
 834        else
 835                width = max_change;
 836
 837        for (i = 0; i < data->nr; i++) {
 838                const char *prefix = "";
 839                char *name = data->files[i]->name;
 840                int added = data->files[i]->added;
 841                int deleted = data->files[i]->deleted;
 842                int name_len;
 843
 844                /*
 845                 * "scale" the filename
 846                 */
 847                len = name_width;
 848                name_len = strlen(name);
 849                if (name_width < name_len) {
 850                        char *slash;
 851                        prefix = "...";
 852                        len -= 3;
 853                        name += name_len - len;
 854                        slash = strchr(name, '/');
 855                        if (slash)
 856                                name = slash;
 857                }
 858
 859                if (data->files[i]->is_binary) {
 860                        show_name(prefix, name, len, reset, set);
 861                        printf("  Bin ");
 862                        printf("%s%d%s", del_c, deleted, reset);
 863                        printf(" -> ");
 864                        printf("%s%d%s", add_c, added, reset);
 865                        printf(" bytes");
 866                        printf("\n");
 867                        goto free_diffstat_file;
 868                }
 869                else if (data->files[i]->is_unmerged) {
 870                        show_name(prefix, name, len, reset, set);
 871                        printf("  Unmerged\n");
 872                        goto free_diffstat_file;
 873                }
 874                else if (!data->files[i]->is_renamed &&
 875                         (added + deleted == 0)) {
 876                        total_files--;
 877                        goto free_diffstat_file;
 878                }
 879
 880                /*
 881                 * scale the add/delete
 882                 */
 883                add = added;
 884                del = deleted;
 885                total = add + del;
 886                adds += add;
 887                dels += del;
 888
 889                if (width <= max_change) {
 890                        add = scale_linear(add, width, max_change);
 891                        del = scale_linear(del, width, max_change);
 892                        total = add + del;
 893                }
 894                show_name(prefix, name, len, reset, set);
 895                printf("%5d ", added + deleted);
 896                show_graph('+', add, add_c, reset);
 897                show_graph('-', del, del_c, reset);
 898                putchar('\n');
 899        free_diffstat_file:
 900                free(data->files[i]->name);
 901                free(data->files[i]);
 902        }
 903        free(data->files);
 904        printf("%s %d files changed, %d insertions(+), %d deletions(-)%s\n",
 905               set, total_files, adds, dels, reset);
 906}
 907
 908static void show_shortstats(struct diffstat_t* data)
 909{
 910        int i, adds = 0, dels = 0, total_files = data->nr;
 911
 912        if (data->nr == 0)
 913                return;
 914
 915        for (i = 0; i < data->nr; i++) {
 916                if (!data->files[i]->is_binary &&
 917                    !data->files[i]->is_unmerged) {
 918                        int added = data->files[i]->added;
 919                        int deleted= data->files[i]->deleted;
 920                        if (!data->files[i]->is_renamed &&
 921                            (added + deleted == 0)) {
 922                                total_files--;
 923                        } else {
 924                                adds += added;
 925                                dels += deleted;
 926                        }
 927                }
 928                free(data->files[i]->name);
 929                free(data->files[i]);
 930        }
 931        free(data->files);
 932
 933        printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
 934               total_files, adds, dels);
 935}
 936
 937static void show_numstat(struct diffstat_t* data, struct diff_options *options)
 938{
 939        int i;
 940
 941        for (i = 0; i < data->nr; i++) {
 942                struct diffstat_file *file = data->files[i];
 943
 944                if (file->is_binary)
 945                        printf("-\t-\t");
 946                else
 947                        printf("%d\t%d\t", file->added, file->deleted);
 948                if (options->line_termination && !file->is_renamed &&
 949                    quote_c_style(file->name, NULL, NULL, 0))
 950                        quote_c_style(file->name, NULL, stdout, 0);
 951                else
 952                        fputs(file->name, stdout);
 953                putchar(options->line_termination);
 954        }
 955}
 956
 957struct checkdiff_t {
 958        struct xdiff_emit_state xm;
 959        const char *filename;
 960        int lineno, color_diff;
 961};
 962
 963static void checkdiff_consume(void *priv, char *line, unsigned long len)
 964{
 965        struct checkdiff_t *data = priv;
 966        const char *ws = diff_get_color(data->color_diff, DIFF_WHITESPACE);
 967        const char *reset = diff_get_color(data->color_diff, DIFF_RESET);
 968        const char *set = diff_get_color(data->color_diff, DIFF_FILE_NEW);
 969
 970        if (line[0] == '+') {
 971                int i, spaces = 0, space_before_tab = 0, white_space_at_end = 0;
 972
 973                /* check space before tab */
 974                for (i = 1; i < len && (line[i] == ' ' || line[i] == '\t'); i++)
 975                        if (line[i] == ' ')
 976                                spaces++;
 977                if (line[i - 1] == '\t' && spaces)
 978                        space_before_tab = 1;
 979
 980                /* check white space at line end */
 981                if (line[len - 1] == '\n')
 982                        len--;
 983                if (isspace(line[len - 1]))
 984                        white_space_at_end = 1;
 985
 986                if (space_before_tab || white_space_at_end) {
 987                        printf("%s:%d: %s", data->filename, data->lineno, ws);
 988                        if (space_before_tab) {
 989                                printf("space before tab");
 990                                if (white_space_at_end)
 991                                        putchar(',');
 992                        }
 993                        if (white_space_at_end)
 994                                printf("white space at end");
 995                        printf(":%s ", reset);
 996                        emit_line_with_ws(1, set, reset, ws, line, len);
 997                }
 998
 999                data->lineno++;
1000        } else if (line[0] == ' ')
1001                data->lineno++;
1002        else if (line[0] == '@') {
1003                char *plus = strchr(line, '+');
1004                if (plus)
1005                        data->lineno = strtol(plus, NULL, 10);
1006                else
1007                        die("invalid diff");
1008        }
1009}
1010
1011static unsigned char *deflate_it(char *data,
1012                                 unsigned long size,
1013                                 unsigned long *result_size)
1014{
1015        int bound;
1016        unsigned char *deflated;
1017        z_stream stream;
1018
1019        memset(&stream, 0, sizeof(stream));
1020        deflateInit(&stream, zlib_compression_level);
1021        bound = deflateBound(&stream, size);
1022        deflated = xmalloc(bound);
1023        stream.next_out = deflated;
1024        stream.avail_out = bound;
1025
1026        stream.next_in = (unsigned char *)data;
1027        stream.avail_in = size;
1028        while (deflate(&stream, Z_FINISH) == Z_OK)
1029                ; /* nothing */
1030        deflateEnd(&stream);
1031        *result_size = stream.total_out;
1032        return deflated;
1033}
1034
1035static void emit_binary_diff_body(mmfile_t *one, mmfile_t *two)
1036{
1037        void *cp;
1038        void *delta;
1039        void *deflated;
1040        void *data;
1041        unsigned long orig_size;
1042        unsigned long delta_size;
1043        unsigned long deflate_size;
1044        unsigned long data_size;
1045
1046        /* We could do deflated delta, or we could do just deflated two,
1047         * whichever is smaller.
1048         */
1049        delta = NULL;
1050        deflated = deflate_it(two->ptr, two->size, &deflate_size);
1051        if (one->size && two->size) {
1052                delta = diff_delta(one->ptr, one->size,
1053                                   two->ptr, two->size,
1054                                   &delta_size, deflate_size);
1055                if (delta) {
1056                        void *to_free = delta;
1057                        orig_size = delta_size;
1058                        delta = deflate_it(delta, delta_size, &delta_size);
1059                        free(to_free);
1060                }
1061        }
1062
1063        if (delta && delta_size < deflate_size) {
1064                printf("delta %lu\n", orig_size);
1065                free(deflated);
1066                data = delta;
1067                data_size = delta_size;
1068        }
1069        else {
1070                printf("literal %lu\n", two->size);
1071                free(delta);
1072                data = deflated;
1073                data_size = deflate_size;
1074        }
1075
1076        /* emit data encoded in base85 */
1077        cp = data;
1078        while (data_size) {
1079                int bytes = (52 < data_size) ? 52 : data_size;
1080                char line[70];
1081                data_size -= bytes;
1082                if (bytes <= 26)
1083                        line[0] = bytes + 'A' - 1;
1084                else
1085                        line[0] = bytes - 26 + 'a' - 1;
1086                encode_85(line + 1, cp, bytes);
1087                cp = (char *) cp + bytes;
1088                puts(line);
1089        }
1090        printf("\n");
1091        free(data);
1092}
1093
1094static void emit_binary_diff(mmfile_t *one, mmfile_t *two)
1095{
1096        printf("GIT binary patch\n");
1097        emit_binary_diff_body(one, two);
1098        emit_binary_diff_body(two, one);
1099}
1100
1101static void setup_diff_attr_check(struct git_attr_check *check)
1102{
1103        static struct git_attr *attr_diff;
1104
1105        if (!attr_diff) {
1106                attr_diff = git_attr("diff", 4);
1107        }
1108        check[0].attr = attr_diff;
1109}
1110
1111static void diff_filespec_check_attr(struct diff_filespec *one)
1112{
1113        struct git_attr_check attr_diff_check[1];
1114
1115        if (one->checked_attr)
1116                return;
1117
1118        setup_diff_attr_check(attr_diff_check);
1119        one->is_binary = 0;
1120
1121        if (!git_checkattr(one->path, ARRAY_SIZE(attr_diff_check), attr_diff_check)) {
1122                const char *value;
1123
1124                /* binaryness */
1125                value = attr_diff_check[0].value;
1126                if (ATTR_TRUE(value))
1127                        ;
1128                else if (ATTR_FALSE(value))
1129                        one->is_binary = 1;
1130        }
1131
1132        if (!one->data && DIFF_FILE_VALID(one))
1133                diff_populate_filespec(one, 0);
1134
1135        if (one->data)
1136                one->is_binary = buffer_is_binary(one->data, one->size);
1137
1138}
1139
1140int diff_filespec_is_binary(struct diff_filespec *one)
1141{
1142        diff_filespec_check_attr(one);
1143        return one->is_binary;
1144}
1145
1146static void builtin_diff(const char *name_a,
1147                         const char *name_b,
1148                         struct diff_filespec *one,
1149                         struct diff_filespec *two,
1150                         const char *xfrm_msg,
1151                         struct diff_options *o,
1152                         int complete_rewrite)
1153{
1154        mmfile_t mf1, mf2;
1155        const char *lbl[2];
1156        char *a_one, *b_two;
1157        const char *set = diff_get_color(o->color_diff, DIFF_METAINFO);
1158        const char *reset = diff_get_color(o->color_diff, DIFF_RESET);
1159
1160        a_one = quote_two("a/", name_a + (*name_a == '/'));
1161        b_two = quote_two("b/", name_b + (*name_b == '/'));
1162        lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
1163        lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
1164        printf("%sdiff --git %s %s%s\n", set, a_one, b_two, reset);
1165        if (lbl[0][0] == '/') {
1166                /* /dev/null */
1167                printf("%snew file mode %06o%s\n", set, two->mode, reset);
1168                if (xfrm_msg && xfrm_msg[0])
1169                        printf("%s%s%s\n", set, xfrm_msg, reset);
1170        }
1171        else if (lbl[1][0] == '/') {
1172                printf("%sdeleted file mode %06o%s\n", set, one->mode, reset);
1173                if (xfrm_msg && xfrm_msg[0])
1174                        printf("%s%s%s\n", set, xfrm_msg, reset);
1175        }
1176        else {
1177                if (one->mode != two->mode) {
1178                        printf("%sold mode %06o%s\n", set, one->mode, reset);
1179                        printf("%snew mode %06o%s\n", set, two->mode, reset);
1180                }
1181                if (xfrm_msg && xfrm_msg[0])
1182                        printf("%s%s%s\n", set, xfrm_msg, reset);
1183                /*
1184                 * we do not run diff between different kind
1185                 * of objects.
1186                 */
1187                if ((one->mode ^ two->mode) & S_IFMT)
1188                        goto free_ab_and_return;
1189                if (complete_rewrite) {
1190                        emit_rewrite_diff(name_a, name_b, one, two,
1191                                        o->color_diff);
1192                        o->found_changes = 1;
1193                        goto free_ab_and_return;
1194                }
1195        }
1196
1197        if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1198                die("unable to read files to diff");
1199
1200        if (!o->text &&
1201            (diff_filespec_is_binary(one) || diff_filespec_is_binary(two))) {
1202                /* Quite common confusing case */
1203                if (mf1.size == mf2.size &&
1204                    !memcmp(mf1.ptr, mf2.ptr, mf1.size))
1205                        goto free_ab_and_return;
1206                if (o->binary)
1207                        emit_binary_diff(&mf1, &mf2);
1208                else
1209                        printf("Binary files %s and %s differ\n",
1210                               lbl[0], lbl[1]);
1211                o->found_changes = 1;
1212        }
1213        else {
1214                /* Crazy xdl interfaces.. */
1215                const char *diffopts = getenv("GIT_DIFF_OPTS");
1216                xpparam_t xpp;
1217                xdemitconf_t xecfg;
1218                xdemitcb_t ecb;
1219                struct emit_callback ecbdata;
1220
1221                memset(&xecfg, 0, sizeof(xecfg));
1222                memset(&ecbdata, 0, sizeof(ecbdata));
1223                ecbdata.label_path = lbl;
1224                ecbdata.color_diff = o->color_diff;
1225                ecbdata.found_changesp = &o->found_changes;
1226                xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1227                xecfg.ctxlen = o->context;
1228                xecfg.flags = XDL_EMIT_FUNCNAMES;
1229                if (!diffopts)
1230                        ;
1231                else if (!prefixcmp(diffopts, "--unified="))
1232                        xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
1233                else if (!prefixcmp(diffopts, "-u"))
1234                        xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
1235                ecb.outf = xdiff_outf;
1236                ecb.priv = &ecbdata;
1237                ecbdata.xm.consume = fn_out_consume;
1238                if (o->color_diff_words)
1239                        ecbdata.diff_words =
1240                                xcalloc(1, sizeof(struct diff_words_data));
1241                xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1242                if (o->color_diff_words)
1243                        free_diff_words_data(&ecbdata);
1244        }
1245
1246 free_ab_and_return:
1247        diff_free_filespec_data(one);
1248        diff_free_filespec_data(two);
1249        free(a_one);
1250        free(b_two);
1251        return;
1252}
1253
1254static void builtin_diffstat(const char *name_a, const char *name_b,
1255                             struct diff_filespec *one,
1256                             struct diff_filespec *two,
1257                             struct diffstat_t *diffstat,
1258                             struct diff_options *o,
1259                             int complete_rewrite)
1260{
1261        mmfile_t mf1, mf2;
1262        struct diffstat_file *data;
1263
1264        data = diffstat_add(diffstat, name_a, name_b);
1265
1266        if (!one || !two) {
1267                data->is_unmerged = 1;
1268                return;
1269        }
1270        if (complete_rewrite) {
1271                diff_populate_filespec(one, 0);
1272                diff_populate_filespec(two, 0);
1273                data->deleted = count_lines(one->data, one->size);
1274                data->added = count_lines(two->data, two->size);
1275                goto free_and_return;
1276        }
1277        if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1278                die("unable to read files to diff");
1279
1280        if (diff_filespec_is_binary(one) || diff_filespec_is_binary(two)) {
1281                data->is_binary = 1;
1282                data->added = mf2.size;
1283                data->deleted = mf1.size;
1284        } else {
1285                /* Crazy xdl interfaces.. */
1286                xpparam_t xpp;
1287                xdemitconf_t xecfg;
1288                xdemitcb_t ecb;
1289
1290                memset(&xecfg, 0, sizeof(xecfg));
1291                xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts;
1292                ecb.outf = xdiff_outf;
1293                ecb.priv = diffstat;
1294                xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1295        }
1296
1297 free_and_return:
1298        diff_free_filespec_data(one);
1299        diff_free_filespec_data(two);
1300}
1301
1302static void builtin_checkdiff(const char *name_a, const char *name_b,
1303                             struct diff_filespec *one,
1304                             struct diff_filespec *two, struct diff_options *o)
1305{
1306        mmfile_t mf1, mf2;
1307        struct checkdiff_t data;
1308
1309        if (!two)
1310                return;
1311
1312        memset(&data, 0, sizeof(data));
1313        data.xm.consume = checkdiff_consume;
1314        data.filename = name_b ? name_b : name_a;
1315        data.lineno = 0;
1316        data.color_diff = o->color_diff;
1317
1318        if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
1319                die("unable to read files to diff");
1320
1321        if (diff_filespec_is_binary(two))
1322                goto free_and_return;
1323        else {
1324                /* Crazy xdl interfaces.. */
1325                xpparam_t xpp;
1326                xdemitconf_t xecfg;
1327                xdemitcb_t ecb;
1328
1329                memset(&xecfg, 0, sizeof(xecfg));
1330                xpp.flags = XDF_NEED_MINIMAL;
1331                ecb.outf = xdiff_outf;
1332                ecb.priv = &data;
1333                xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
1334        }
1335 free_and_return:
1336        diff_free_filespec_data(one);
1337        diff_free_filespec_data(two);
1338}
1339
1340struct diff_filespec *alloc_filespec(const char *path)
1341{
1342        int namelen = strlen(path);
1343        struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
1344
1345        memset(spec, 0, sizeof(*spec));
1346        spec->path = (char *)(spec + 1);
1347        memcpy(spec->path, path, namelen+1);
1348        return spec;
1349}
1350
1351void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
1352                   unsigned short mode)
1353{
1354        if (mode) {
1355                spec->mode = canon_mode(mode);
1356                hashcpy(spec->sha1, sha1);
1357                spec->sha1_valid = !is_null_sha1(sha1);
1358        }
1359}
1360
1361/*
1362 * Given a name and sha1 pair, if the index tells us the file in
1363 * the work tree has that object contents, return true, so that
1364 * prepare_temp_file() does not have to inflate and extract.
1365 */
1366static int reuse_worktree_file(const char *name, const unsigned char *sha1, int want_file)
1367{
1368        struct cache_entry *ce;
1369        struct stat st;
1370        int pos, len;
1371
1372        /* We do not read the cache ourselves here, because the
1373         * benchmark with my previous version that always reads cache
1374         * shows that it makes things worse for diff-tree comparing
1375         * two linux-2.6 kernel trees in an already checked out work
1376         * tree.  This is because most diff-tree comparisons deal with
1377         * only a small number of files, while reading the cache is
1378         * expensive for a large project, and its cost outweighs the
1379         * savings we get by not inflating the object to a temporary
1380         * file.  Practically, this code only helps when we are used
1381         * by diff-cache --cached, which does read the cache before
1382         * calling us.
1383         */
1384        if (!active_cache)
1385                return 0;
1386
1387        /* We want to avoid the working directory if our caller
1388         * doesn't need the data in a normal file, this system
1389         * is rather slow with its stat/open/mmap/close syscalls,
1390         * and the object is contained in a pack file.  The pack
1391         * is probably already open and will be faster to obtain
1392         * the data through than the working directory.  Loose
1393         * objects however would tend to be slower as they need
1394         * to be individually opened and inflated.
1395         */
1396        if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(sha1, NULL))
1397                return 0;
1398
1399        len = strlen(name);
1400        pos = cache_name_pos(name, len);
1401        if (pos < 0)
1402                return 0;
1403        ce = active_cache[pos];
1404        if ((lstat(name, &st) < 0) ||
1405            !S_ISREG(st.st_mode) || /* careful! */
1406            ce_match_stat(ce, &st, 0) ||
1407            hashcmp(sha1, ce->sha1))
1408                return 0;
1409        /* we return 1 only when we can stat, it is a regular file,
1410         * stat information matches, and sha1 recorded in the cache
1411         * matches.  I.e. we know the file in the work tree really is
1412         * the same as the <name, sha1> pair.
1413         */
1414        return 1;
1415}
1416
1417static int populate_from_stdin(struct diff_filespec *s)
1418{
1419#define INCREMENT 1024
1420        char *buf;
1421        unsigned long size;
1422        ssize_t got;
1423
1424        size = 0;
1425        buf = NULL;
1426        while (1) {
1427                buf = xrealloc(buf, size + INCREMENT);
1428                got = xread(0, buf + size, INCREMENT);
1429                if (!got)
1430                        break; /* EOF */
1431                if (got < 0)
1432                        return error("error while reading from stdin %s",
1433                                     strerror(errno));
1434                size += got;
1435        }
1436        s->should_munmap = 0;
1437        s->data = buf;
1438        s->size = size;
1439        s->should_free = 1;
1440        return 0;
1441}
1442
1443static int diff_populate_gitlink(struct diff_filespec *s, int size_only)
1444{
1445        int len;
1446        char *data = xmalloc(100);
1447        len = snprintf(data, 100,
1448                "Subproject commit %s\n", sha1_to_hex(s->sha1));
1449        s->data = data;
1450        s->size = len;
1451        s->should_free = 1;
1452        if (size_only) {
1453                s->data = NULL;
1454                free(data);
1455        }
1456        return 0;
1457}
1458
1459/*
1460 * While doing rename detection and pickaxe operation, we may need to
1461 * grab the data for the blob (or file) for our own in-core comparison.
1462 * diff_filespec has data and size fields for this purpose.
1463 */
1464int diff_populate_filespec(struct diff_filespec *s, int size_only)
1465{
1466        int err = 0;
1467        if (!DIFF_FILE_VALID(s))
1468                die("internal error: asking to populate invalid file.");
1469        if (S_ISDIR(s->mode))
1470                return -1;
1471
1472        if (s->data)
1473                return 0;
1474
1475        if (size_only && 0 < s->size)
1476                return 0;
1477
1478        if (S_ISGITLINK(s->mode))
1479                return diff_populate_gitlink(s, size_only);
1480
1481        if (!s->sha1_valid ||
1482            reuse_worktree_file(s->path, s->sha1, 0)) {
1483                struct stat st;
1484                int fd;
1485                char *buf;
1486                unsigned long size;
1487
1488                if (!strcmp(s->path, "-"))
1489                        return populate_from_stdin(s);
1490
1491                if (lstat(s->path, &st) < 0) {
1492                        if (errno == ENOENT) {
1493                        err_empty:
1494                                err = -1;
1495                        empty:
1496                                s->data = (char *)"";
1497                                s->size = 0;
1498                                return err;
1499                        }
1500                }
1501                s->size = xsize_t(st.st_size);
1502                if (!s->size)
1503                        goto empty;
1504                if (size_only)
1505                        return 0;
1506                if (S_ISLNK(st.st_mode)) {
1507                        int ret;
1508                        s->data = xmalloc(s->size);
1509                        s->should_free = 1;
1510                        ret = readlink(s->path, s->data, s->size);
1511                        if (ret < 0) {
1512                                free(s->data);
1513                                goto err_empty;
1514                        }
1515                        return 0;
1516                }
1517                fd = open(s->path, O_RDONLY);
1518                if (fd < 0)
1519                        goto err_empty;
1520                s->data = xmmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
1521                close(fd);
1522                s->should_munmap = 1;
1523
1524                /*
1525                 * Convert from working tree format to canonical git format
1526                 */
1527                size = s->size;
1528                buf = convert_to_git(s->path, s->data, &size);
1529                if (buf) {
1530                        munmap(s->data, s->size);
1531                        s->should_munmap = 0;
1532                        s->data = buf;
1533                        s->size = size;
1534                        s->should_free = 1;
1535                }
1536        }
1537        else {
1538                enum object_type type;
1539                if (size_only)
1540                        type = sha1_object_info(s->sha1, &s->size);
1541                else {
1542                        s->data = read_sha1_file(s->sha1, &type, &s->size);
1543                        s->should_free = 1;
1544                }
1545        }
1546        return 0;
1547}
1548
1549void diff_free_filespec_data(struct diff_filespec *s)
1550{
1551        if (s->should_free)
1552                free(s->data);
1553        else if (s->should_munmap)
1554                munmap(s->data, s->size);
1555
1556        if (s->should_free || s->should_munmap) {
1557                s->should_free = s->should_munmap = 0;
1558                s->data = NULL;
1559        }
1560        free(s->cnt_data);
1561        s->cnt_data = NULL;
1562}
1563
1564static void prep_temp_blob(struct diff_tempfile *temp,
1565                           void *blob,
1566                           unsigned long size,
1567                           const unsigned char *sha1,
1568                           int mode)
1569{
1570        int fd;
1571
1572        fd = git_mkstemp(temp->tmp_path, PATH_MAX, ".diff_XXXXXX");
1573        if (fd < 0)
1574                die("unable to create temp-file");
1575        if (write_in_full(fd, blob, size) != size)
1576                die("unable to write temp-file");
1577        close(fd);
1578        temp->name = temp->tmp_path;
1579        strcpy(temp->hex, sha1_to_hex(sha1));
1580        temp->hex[40] = 0;
1581        sprintf(temp->mode, "%06o", mode);
1582}
1583
1584static void prepare_temp_file(const char *name,
1585                              struct diff_tempfile *temp,
1586                              struct diff_filespec *one)
1587{
1588        if (!DIFF_FILE_VALID(one)) {
1589        not_a_valid_file:
1590                /* A '-' entry produces this for file-2, and
1591                 * a '+' entry produces this for file-1.
1592                 */
1593                temp->name = "/dev/null";
1594                strcpy(temp->hex, ".");
1595                strcpy(temp->mode, ".");
1596                return;
1597        }
1598
1599        if (!one->sha1_valid ||
1600            reuse_worktree_file(name, one->sha1, 1)) {
1601                struct stat st;
1602                if (lstat(name, &st) < 0) {
1603                        if (errno == ENOENT)
1604                                goto not_a_valid_file;
1605                        die("stat(%s): %s", name, strerror(errno));
1606                }
1607                if (S_ISLNK(st.st_mode)) {
1608                        int ret;
1609                        char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
1610                        size_t sz = xsize_t(st.st_size);
1611                        if (sizeof(buf) <= st.st_size)
1612                                die("symlink too long: %s", name);
1613                        ret = readlink(name, buf, sz);
1614                        if (ret < 0)
1615                                die("readlink(%s)", name);
1616                        prep_temp_blob(temp, buf, sz,
1617                                       (one->sha1_valid ?
1618                                        one->sha1 : null_sha1),
1619                                       (one->sha1_valid ?
1620                                        one->mode : S_IFLNK));
1621                }
1622                else {
1623                        /* we can borrow from the file in the work tree */
1624                        temp->name = name;
1625                        if (!one->sha1_valid)
1626                                strcpy(temp->hex, sha1_to_hex(null_sha1));
1627                        else
1628                                strcpy(temp->hex, sha1_to_hex(one->sha1));
1629                        /* Even though we may sometimes borrow the
1630                         * contents from the work tree, we always want
1631                         * one->mode.  mode is trustworthy even when
1632                         * !(one->sha1_valid), as long as
1633                         * DIFF_FILE_VALID(one).
1634                         */
1635                        sprintf(temp->mode, "%06o", one->mode);
1636                }
1637                return;
1638        }
1639        else {
1640                if (diff_populate_filespec(one, 0))
1641                        die("cannot read data blob for %s", one->path);
1642                prep_temp_blob(temp, one->data, one->size,
1643                               one->sha1, one->mode);
1644        }
1645}
1646
1647static void remove_tempfile(void)
1648{
1649        int i;
1650
1651        for (i = 0; i < 2; i++)
1652                if (diff_temp[i].name == diff_temp[i].tmp_path) {
1653                        unlink(diff_temp[i].name);
1654                        diff_temp[i].name = NULL;
1655                }
1656}
1657
1658static void remove_tempfile_on_signal(int signo)
1659{
1660        remove_tempfile();
1661        signal(SIGINT, SIG_DFL);
1662        raise(signo);
1663}
1664
1665static int spawn_prog(const char *pgm, const char **arg)
1666{
1667        pid_t pid;
1668        int status;
1669
1670        fflush(NULL);
1671        pid = fork();
1672        if (pid < 0)
1673                die("unable to fork");
1674        if (!pid) {
1675                execvp(pgm, (char *const*) arg);
1676                exit(255);
1677        }
1678
1679        while (waitpid(pid, &status, 0) < 0) {
1680                if (errno == EINTR)
1681                        continue;
1682                return -1;
1683        }
1684
1685        /* Earlier we did not check the exit status because
1686         * diff exits non-zero if files are different, and
1687         * we are not interested in knowing that.  It was a
1688         * mistake which made it harder to quit a diff-*
1689         * session that uses the git-apply-patch-script as
1690         * the GIT_EXTERNAL_DIFF.  A custom GIT_EXTERNAL_DIFF
1691         * should also exit non-zero only when it wants to
1692         * abort the entire diff-* session.
1693         */
1694        if (WIFEXITED(status) && !WEXITSTATUS(status))
1695                return 0;
1696        return -1;
1697}
1698
1699/* An external diff command takes:
1700 *
1701 * diff-cmd name infile1 infile1-sha1 infile1-mode \
1702 *               infile2 infile2-sha1 infile2-mode [ rename-to ]
1703 *
1704 */
1705static void run_external_diff(const char *pgm,
1706                              const char *name,
1707                              const char *other,
1708                              struct diff_filespec *one,
1709                              struct diff_filespec *two,
1710                              const char *xfrm_msg,
1711                              int complete_rewrite)
1712{
1713        const char *spawn_arg[10];
1714        struct diff_tempfile *temp = diff_temp;
1715        int retval;
1716        static int atexit_asked = 0;
1717        const char *othername;
1718        const char **arg = &spawn_arg[0];
1719
1720        othername = (other? other : name);
1721        if (one && two) {
1722                prepare_temp_file(name, &temp[0], one);
1723                prepare_temp_file(othername, &temp[1], two);
1724                if (! atexit_asked &&
1725                    (temp[0].name == temp[0].tmp_path ||
1726                     temp[1].name == temp[1].tmp_path)) {
1727                        atexit_asked = 1;
1728                        atexit(remove_tempfile);
1729                }
1730                signal(SIGINT, remove_tempfile_on_signal);
1731        }
1732
1733        if (one && two) {
1734                *arg++ = pgm;
1735                *arg++ = name;
1736                *arg++ = temp[0].name;
1737                *arg++ = temp[0].hex;
1738                *arg++ = temp[0].mode;
1739                *arg++ = temp[1].name;
1740                *arg++ = temp[1].hex;
1741                *arg++ = temp[1].mode;
1742                if (other) {
1743                        *arg++ = other;
1744                        *arg++ = xfrm_msg;
1745                }
1746        } else {
1747                *arg++ = pgm;
1748                *arg++ = name;
1749        }
1750        *arg = NULL;
1751        retval = spawn_prog(pgm, spawn_arg);
1752        remove_tempfile();
1753        if (retval) {
1754                fprintf(stderr, "external diff died, stopping at %s.\n", name);
1755                exit(1);
1756        }
1757}
1758
1759static const char *external_diff_attr(const char *name)
1760{
1761        struct git_attr_check attr_diff_check;
1762
1763        setup_diff_attr_check(&attr_diff_check);
1764        if (!git_checkattr(name, 1, &attr_diff_check)) {
1765                const char *value = attr_diff_check.value;
1766                if (!ATTR_TRUE(value) &&
1767                    !ATTR_FALSE(value) &&
1768                    !ATTR_UNSET(value)) {
1769                        struct ll_diff_driver *drv;
1770
1771                        if (!user_diff_tail) {
1772                                user_diff_tail = &user_diff;
1773                                git_config(git_diff_ui_config);
1774                        }
1775                        for (drv = user_diff; drv; drv = drv->next)
1776                                if (!strcmp(drv->name, value))
1777                                        return drv->cmd;
1778                }
1779        }
1780        return NULL;
1781}
1782
1783static void run_diff_cmd(const char *pgm,
1784                         const char *name,
1785                         const char *other,
1786                         struct diff_filespec *one,
1787                         struct diff_filespec *two,
1788                         const char *xfrm_msg,
1789                         struct diff_options *o,
1790                         int complete_rewrite)
1791{
1792        if (!o->allow_external)
1793                pgm = NULL;
1794        else {
1795                const char *cmd = external_diff_attr(name);
1796                if (cmd)
1797                        pgm = cmd;
1798        }
1799
1800        if (pgm) {
1801                run_external_diff(pgm, name, other, one, two, xfrm_msg,
1802                                  complete_rewrite);
1803                return;
1804        }
1805        if (one && two)
1806                builtin_diff(name, other ? other : name,
1807                             one, two, xfrm_msg, o, complete_rewrite);
1808        else
1809                printf("* Unmerged path %s\n", name);
1810}
1811
1812static void diff_fill_sha1_info(struct diff_filespec *one)
1813{
1814        if (DIFF_FILE_VALID(one)) {
1815                if (!one->sha1_valid) {
1816                        struct stat st;
1817                        if (!strcmp(one->path, "-")) {
1818                                hashcpy(one->sha1, null_sha1);
1819                                return;
1820                        }
1821                        if (lstat(one->path, &st) < 0)
1822                                die("stat %s", one->path);
1823                        if (index_path(one->sha1, one->path, &st, 0))
1824                                die("cannot hash %s\n", one->path);
1825                }
1826        }
1827        else
1828                hashclr(one->sha1);
1829}
1830
1831static int similarity_index(struct diff_filepair *p)
1832{
1833        return p->score * 100 / MAX_SCORE;
1834}
1835
1836static void run_diff(struct diff_filepair *p, struct diff_options *o)
1837{
1838        const char *pgm = external_diff();
1839        char msg[PATH_MAX*2+300], *xfrm_msg;
1840        struct diff_filespec *one;
1841        struct diff_filespec *two;
1842        const char *name;
1843        const char *other;
1844        char *name_munged, *other_munged;
1845        int complete_rewrite = 0;
1846        int len;
1847
1848        if (DIFF_PAIR_UNMERGED(p)) {
1849                /* unmerged */
1850                run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, o, 0);
1851                return;
1852        }
1853
1854        name = p->one->path;
1855        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1856        name_munged = quote_one(name);
1857        other_munged = quote_one(other);
1858        one = p->one; two = p->two;
1859
1860        diff_fill_sha1_info(one);
1861        diff_fill_sha1_info(two);
1862
1863        len = 0;
1864        switch (p->status) {
1865        case DIFF_STATUS_COPIED:
1866                len += snprintf(msg + len, sizeof(msg) - len,
1867                                "similarity index %d%%\n"
1868                                "copy from %s\n"
1869                                "copy to %s\n",
1870                                similarity_index(p), name_munged, other_munged);
1871                break;
1872        case DIFF_STATUS_RENAMED:
1873                len += snprintf(msg + len, sizeof(msg) - len,
1874                                "similarity index %d%%\n"
1875                                "rename from %s\n"
1876                                "rename to %s\n",
1877                                similarity_index(p), name_munged, other_munged);
1878                break;
1879        case DIFF_STATUS_MODIFIED:
1880                if (p->score) {
1881                        len += snprintf(msg + len, sizeof(msg) - len,
1882                                        "dissimilarity index %d%%\n",
1883                                        similarity_index(p));
1884                        complete_rewrite = 1;
1885                        break;
1886                }
1887                /* fallthru */
1888        default:
1889                /* nothing */
1890                ;
1891        }
1892
1893        if (hashcmp(one->sha1, two->sha1)) {
1894                int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
1895
1896                if (o->binary) {
1897                        mmfile_t mf;
1898                        if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
1899                            (!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
1900                                abbrev = 40;
1901                }
1902                len += snprintf(msg + len, sizeof(msg) - len,
1903                                "index %.*s..%.*s",
1904                                abbrev, sha1_to_hex(one->sha1),
1905                                abbrev, sha1_to_hex(two->sha1));
1906                if (one->mode == two->mode)
1907                        len += snprintf(msg + len, sizeof(msg) - len,
1908                                        " %06o", one->mode);
1909                len += snprintf(msg + len, sizeof(msg) - len, "\n");
1910        }
1911
1912        if (len)
1913                msg[--len] = 0;
1914        xfrm_msg = len ? msg : NULL;
1915
1916        if (!pgm &&
1917            DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
1918            (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
1919                /* a filepair that changes between file and symlink
1920                 * needs to be split into deletion and creation.
1921                 */
1922                struct diff_filespec *null = alloc_filespec(two->path);
1923                run_diff_cmd(NULL, name, other, one, null, xfrm_msg, o, 0);
1924                free(null);
1925                null = alloc_filespec(one->path);
1926                run_diff_cmd(NULL, name, other, null, two, xfrm_msg, o, 0);
1927                free(null);
1928        }
1929        else
1930                run_diff_cmd(pgm, name, other, one, two, xfrm_msg, o,
1931                             complete_rewrite);
1932
1933        free(name_munged);
1934        free(other_munged);
1935}
1936
1937static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
1938                         struct diffstat_t *diffstat)
1939{
1940        const char *name;
1941        const char *other;
1942        int complete_rewrite = 0;
1943
1944        if (DIFF_PAIR_UNMERGED(p)) {
1945                /* unmerged */
1946                builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat, o, 0);
1947                return;
1948        }
1949
1950        name = p->one->path;
1951        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1952
1953        diff_fill_sha1_info(p->one);
1954        diff_fill_sha1_info(p->two);
1955
1956        if (p->status == DIFF_STATUS_MODIFIED && p->score)
1957                complete_rewrite = 1;
1958        builtin_diffstat(name, other, p->one, p->two, diffstat, o, complete_rewrite);
1959}
1960
1961static void run_checkdiff(struct diff_filepair *p, struct diff_options *o)
1962{
1963        const char *name;
1964        const char *other;
1965
1966        if (DIFF_PAIR_UNMERGED(p)) {
1967                /* unmerged */
1968                return;
1969        }
1970
1971        name = p->one->path;
1972        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1973
1974        diff_fill_sha1_info(p->one);
1975        diff_fill_sha1_info(p->two);
1976
1977        builtin_checkdiff(name, other, p->one, p->two, o);
1978}
1979
1980void diff_setup(struct diff_options *options)
1981{
1982        memset(options, 0, sizeof(*options));
1983        options->line_termination = '\n';
1984        options->break_opt = -1;
1985        options->rename_limit = -1;
1986        options->context = 3;
1987        options->msg_sep = "";
1988
1989        options->change = diff_change;
1990        options->add_remove = diff_addremove;
1991        options->color_diff = diff_use_color_default;
1992        options->detect_rename = diff_detect_rename_default;
1993}
1994
1995int diff_setup_done(struct diff_options *options)
1996{
1997        int count = 0;
1998
1999        if (options->output_format & DIFF_FORMAT_NAME)
2000                count++;
2001        if (options->output_format & DIFF_FORMAT_NAME_STATUS)
2002                count++;
2003        if (options->output_format & DIFF_FORMAT_CHECKDIFF)
2004                count++;
2005        if (options->output_format & DIFF_FORMAT_NO_OUTPUT)
2006                count++;
2007        if (count > 1)
2008                die("--name-only, --name-status, --check and -s are mutually exclusive");
2009
2010        if (options->find_copies_harder)
2011                options->detect_rename = DIFF_DETECT_COPY;
2012
2013        if (options->output_format & (DIFF_FORMAT_NAME |
2014                                      DIFF_FORMAT_NAME_STATUS |
2015                                      DIFF_FORMAT_CHECKDIFF |
2016                                      DIFF_FORMAT_NO_OUTPUT))
2017                options->output_format &= ~(DIFF_FORMAT_RAW |
2018                                            DIFF_FORMAT_NUMSTAT |
2019                                            DIFF_FORMAT_DIFFSTAT |
2020                                            DIFF_FORMAT_SHORTSTAT |
2021                                            DIFF_FORMAT_SUMMARY |
2022                                            DIFF_FORMAT_PATCH);
2023
2024        /*
2025         * These cases always need recursive; we do not drop caller-supplied
2026         * recursive bits for other formats here.
2027         */
2028        if (options->output_format & (DIFF_FORMAT_PATCH |
2029                                      DIFF_FORMAT_NUMSTAT |
2030                                      DIFF_FORMAT_DIFFSTAT |
2031                                      DIFF_FORMAT_SHORTSTAT |
2032                                      DIFF_FORMAT_SUMMARY |
2033                                      DIFF_FORMAT_CHECKDIFF))
2034                options->recursive = 1;
2035        /*
2036         * Also pickaxe would not work very well if you do not say recursive
2037         */
2038        if (options->pickaxe)
2039                options->recursive = 1;
2040
2041        if (options->detect_rename && options->rename_limit < 0)
2042                options->rename_limit = diff_rename_limit_default;
2043        if (options->setup & DIFF_SETUP_USE_CACHE) {
2044                if (!active_cache)
2045                        /* read-cache does not die even when it fails
2046                         * so it is safe for us to do this here.  Also
2047                         * it does not smudge active_cache or active_nr
2048                         * when it fails, so we do not have to worry about
2049                         * cleaning it up ourselves either.
2050                         */
2051                        read_cache();
2052        }
2053        if (options->abbrev <= 0 || 40 < options->abbrev)
2054                options->abbrev = 40; /* full */
2055
2056        /*
2057         * It does not make sense to show the first hit we happened
2058         * to have found.  It does not make sense not to return with
2059         * exit code in such a case either.
2060         */
2061        if (options->quiet) {
2062                options->output_format = DIFF_FORMAT_NO_OUTPUT;
2063                options->exit_with_status = 1;
2064        }
2065
2066        /*
2067         * If we postprocess in diffcore, we cannot simply return
2068         * upon the first hit.  We need to run diff as usual.
2069         */
2070        if (options->pickaxe || options->filter)
2071                options->quiet = 0;
2072
2073        return 0;
2074}
2075
2076static int opt_arg(const char *arg, int arg_short, const char *arg_long, int *val)
2077{
2078        char c, *eq;
2079        int len;
2080
2081        if (*arg != '-')
2082                return 0;
2083        c = *++arg;
2084        if (!c)
2085                return 0;
2086        if (c == arg_short) {
2087                c = *++arg;
2088                if (!c)
2089                        return 1;
2090                if (val && isdigit(c)) {
2091                        char *end;
2092                        int n = strtoul(arg, &end, 10);
2093                        if (*end)
2094                                return 0;
2095                        *val = n;
2096                        return 1;
2097                }
2098                return 0;
2099        }
2100        if (c != '-')
2101                return 0;
2102        arg++;
2103        eq = strchr(arg, '=');
2104        if (eq)
2105                len = eq - arg;
2106        else
2107                len = strlen(arg);
2108        if (!len || strncmp(arg, arg_long, len))
2109                return 0;
2110        if (eq) {
2111                int n;
2112                char *end;
2113                if (!isdigit(*++eq))
2114                        return 0;
2115                n = strtoul(eq, &end, 10);
2116                if (*end)
2117                        return 0;
2118                *val = n;
2119        }
2120        return 1;
2121}
2122
2123static int diff_scoreopt_parse(const char *opt);
2124
2125int diff_opt_parse(struct diff_options *options, const char **av, int ac)
2126{
2127        const char *arg = av[0];
2128        if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
2129                options->output_format |= DIFF_FORMAT_PATCH;
2130        else if (opt_arg(arg, 'U', "unified", &options->context))
2131                options->output_format |= DIFF_FORMAT_PATCH;
2132        else if (!strcmp(arg, "--raw"))
2133                options->output_format |= DIFF_FORMAT_RAW;
2134        else if (!strcmp(arg, "--patch-with-raw")) {
2135                options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_RAW;
2136        }
2137        else if (!strcmp(arg, "--numstat")) {
2138                options->output_format |= DIFF_FORMAT_NUMSTAT;
2139        }
2140        else if (!strcmp(arg, "--shortstat")) {
2141                options->output_format |= DIFF_FORMAT_SHORTSTAT;
2142        }
2143        else if (!prefixcmp(arg, "--stat")) {
2144                char *end;
2145                int width = options->stat_width;
2146                int name_width = options->stat_name_width;
2147                arg += 6;
2148                end = (char *)arg;
2149
2150                switch (*arg) {
2151                case '-':
2152                        if (!prefixcmp(arg, "-width="))
2153                                width = strtoul(arg + 7, &end, 10);
2154                        else if (!prefixcmp(arg, "-name-width="))
2155                                name_width = strtoul(arg + 12, &end, 10);
2156                        break;
2157                case '=':
2158                        width = strtoul(arg+1, &end, 10);
2159                        if (*end == ',')
2160                                name_width = strtoul(end+1, &end, 10);
2161                }
2162
2163                /* Important! This checks all the error cases! */
2164                if (*end)
2165                        return 0;
2166                options->output_format |= DIFF_FORMAT_DIFFSTAT;
2167                options->stat_name_width = name_width;
2168                options->stat_width = width;
2169        }
2170        else if (!strcmp(arg, "--check"))
2171                options->output_format |= DIFF_FORMAT_CHECKDIFF;
2172        else if (!strcmp(arg, "--summary"))
2173                options->output_format |= DIFF_FORMAT_SUMMARY;
2174        else if (!strcmp(arg, "--patch-with-stat")) {
2175                options->output_format |= DIFF_FORMAT_PATCH | DIFF_FORMAT_DIFFSTAT;
2176        }
2177        else if (!strcmp(arg, "-z"))
2178                options->line_termination = 0;
2179        else if (!prefixcmp(arg, "-l"))
2180                options->rename_limit = strtoul(arg+2, NULL, 10);
2181        else if (!strcmp(arg, "--full-index"))
2182                options->full_index = 1;
2183        else if (!strcmp(arg, "--binary")) {
2184                options->output_format |= DIFF_FORMAT_PATCH;
2185                options->binary = 1;
2186        }
2187        else if (!strcmp(arg, "-a") || !strcmp(arg, "--text")) {
2188                options->text = 1;
2189        }
2190        else if (!strcmp(arg, "--name-only"))
2191                options->output_format |= DIFF_FORMAT_NAME;
2192        else if (!strcmp(arg, "--name-status"))
2193                options->output_format |= DIFF_FORMAT_NAME_STATUS;
2194        else if (!strcmp(arg, "-R"))
2195                options->reverse_diff = 1;
2196        else if (!prefixcmp(arg, "-S"))
2197                options->pickaxe = arg + 2;
2198        else if (!strcmp(arg, "-s")) {
2199                options->output_format |= DIFF_FORMAT_NO_OUTPUT;
2200        }
2201        else if (!prefixcmp(arg, "-O"))
2202                options->orderfile = arg + 2;
2203        else if (!prefixcmp(arg, "--diff-filter="))
2204                options->filter = arg + 14;
2205        else if (!strcmp(arg, "--pickaxe-all"))
2206                options->pickaxe_opts = DIFF_PICKAXE_ALL;
2207        else if (!strcmp(arg, "--pickaxe-regex"))
2208                options->pickaxe_opts = DIFF_PICKAXE_REGEX;
2209        else if (!prefixcmp(arg, "-B")) {
2210                if ((options->break_opt =
2211                     diff_scoreopt_parse(arg)) == -1)
2212                        return -1;
2213        }
2214        else if (!prefixcmp(arg, "-M")) {
2215                if ((options->rename_score =
2216                     diff_scoreopt_parse(arg)) == -1)
2217                        return -1;
2218                options->detect_rename = DIFF_DETECT_RENAME;
2219        }
2220        else if (!prefixcmp(arg, "-C")) {
2221                if (options->detect_rename == DIFF_DETECT_COPY)
2222                        options->find_copies_harder = 1;
2223                if ((options->rename_score =
2224                     diff_scoreopt_parse(arg)) == -1)
2225                        return -1;
2226                options->detect_rename = DIFF_DETECT_COPY;
2227        }
2228        else if (!strcmp(arg, "--find-copies-harder"))
2229                options->find_copies_harder = 1;
2230        else if (!strcmp(arg, "--follow"))
2231                options->follow_renames = 1;
2232        else if (!strcmp(arg, "--abbrev"))
2233                options->abbrev = DEFAULT_ABBREV;
2234        else if (!prefixcmp(arg, "--abbrev=")) {
2235                options->abbrev = strtoul(arg + 9, NULL, 10);
2236                if (options->abbrev < MINIMUM_ABBREV)
2237                        options->abbrev = MINIMUM_ABBREV;
2238                else if (40 < options->abbrev)
2239                        options->abbrev = 40;
2240        }
2241        else if (!strcmp(arg, "--color"))
2242                options->color_diff = 1;
2243        else if (!strcmp(arg, "--no-color"))
2244                options->color_diff = 0;
2245        else if (!strcmp(arg, "-w") || !strcmp(arg, "--ignore-all-space"))
2246                options->xdl_opts |= XDF_IGNORE_WHITESPACE;
2247        else if (!strcmp(arg, "-b") || !strcmp(arg, "--ignore-space-change"))
2248                options->xdl_opts |= XDF_IGNORE_WHITESPACE_CHANGE;
2249        else if (!strcmp(arg, "--ignore-space-at-eol"))
2250                options->xdl_opts |= XDF_IGNORE_WHITESPACE_AT_EOL;
2251        else if (!strcmp(arg, "--color-words"))
2252                options->color_diff = options->color_diff_words = 1;
2253        else if (!strcmp(arg, "--no-renames"))
2254                options->detect_rename = 0;
2255        else if (!strcmp(arg, "--exit-code"))
2256                options->exit_with_status = 1;
2257        else if (!strcmp(arg, "--quiet"))
2258                options->quiet = 1;
2259        else if (!strcmp(arg, "--ext-diff"))
2260                options->allow_external = 1;
2261        else if (!strcmp(arg, "--no-ext-diff"))
2262                options->allow_external = 0;
2263        else
2264                return 0;
2265        return 1;
2266}
2267
2268static int parse_num(const char **cp_p)
2269{
2270        unsigned long num, scale;
2271        int ch, dot;
2272        const char *cp = *cp_p;
2273
2274        num = 0;
2275        scale = 1;
2276        dot = 0;
2277        for(;;) {
2278                ch = *cp;
2279                if ( !dot && ch == '.' ) {
2280                        scale = 1;
2281                        dot = 1;
2282                } else if ( ch == '%' ) {
2283                        scale = dot ? scale*100 : 100;
2284                        cp++;   /* % is always at the end */
2285                        break;
2286                } else if ( ch >= '0' && ch <= '9' ) {
2287                        if ( scale < 100000 ) {
2288                                scale *= 10;
2289                                num = (num*10) + (ch-'0');
2290                        }
2291                } else {
2292                        break;
2293                }
2294                cp++;
2295        }
2296        *cp_p = cp;
2297
2298        /* user says num divided by scale and we say internally that
2299         * is MAX_SCORE * num / scale.
2300         */
2301        return (int)((num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale));
2302}
2303
2304static int diff_scoreopt_parse(const char *opt)
2305{
2306        int opt1, opt2, cmd;
2307
2308        if (*opt++ != '-')
2309                return -1;
2310        cmd = *opt++;
2311        if (cmd != 'M' && cmd != 'C' && cmd != 'B')
2312                return -1; /* that is not a -M, -C nor -B option */
2313
2314        opt1 = parse_num(&opt);
2315        if (cmd != 'B')
2316                opt2 = 0;
2317        else {
2318                if (*opt == 0)
2319                        opt2 = 0;
2320                else if (*opt != '/')
2321                        return -1; /* we expect -B80/99 or -B80 */
2322                else {
2323                        opt++;
2324                        opt2 = parse_num(&opt);
2325                }
2326        }
2327        if (*opt != 0)
2328                return -1;
2329        return opt1 | (opt2 << 16);
2330}
2331
2332struct diff_queue_struct diff_queued_diff;
2333
2334void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
2335{
2336        if (queue->alloc <= queue->nr) {
2337                queue->alloc = alloc_nr(queue->alloc);
2338                queue->queue = xrealloc(queue->queue,
2339                                        sizeof(dp) * queue->alloc);
2340        }
2341        queue->queue[queue->nr++] = dp;
2342}
2343
2344struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
2345                                 struct diff_filespec *one,
2346                                 struct diff_filespec *two)
2347{
2348        struct diff_filepair *dp = xcalloc(1, sizeof(*dp));
2349        dp->one = one;
2350        dp->two = two;
2351        if (queue)
2352                diff_q(queue, dp);
2353        return dp;
2354}
2355
2356void diff_free_filepair(struct diff_filepair *p)
2357{
2358        diff_free_filespec_data(p->one);
2359        diff_free_filespec_data(p->two);
2360        free(p->one);
2361        free(p->two);
2362        free(p);
2363}
2364
2365/* This is different from find_unique_abbrev() in that
2366 * it stuffs the result with dots for alignment.
2367 */
2368const char *diff_unique_abbrev(const unsigned char *sha1, int len)
2369{
2370        int abblen;
2371        const char *abbrev;
2372        if (len == 40)
2373                return sha1_to_hex(sha1);
2374
2375        abbrev = find_unique_abbrev(sha1, len);
2376        if (!abbrev)
2377                return sha1_to_hex(sha1);
2378        abblen = strlen(abbrev);
2379        if (abblen < 37) {
2380                static char hex[41];
2381                if (len < abblen && abblen <= len + 2)
2382                        sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
2383                else
2384                        sprintf(hex, "%s...", abbrev);
2385                return hex;
2386        }
2387        return sha1_to_hex(sha1);
2388}
2389
2390static void diff_flush_raw(struct diff_filepair *p,
2391                           struct diff_options *options)
2392{
2393        int two_paths;
2394        char status[10];
2395        int abbrev = options->abbrev;
2396        const char *path_one, *path_two;
2397        int inter_name_termination = '\t';
2398        int line_termination = options->line_termination;
2399
2400        if (!line_termination)
2401                inter_name_termination = 0;
2402
2403        path_one = p->one->path;
2404        path_two = p->two->path;
2405        if (line_termination) {
2406                path_one = quote_one(path_one);
2407                path_two = quote_one(path_two);
2408        }
2409
2410        if (p->score)
2411                sprintf(status, "%c%03d", p->status, similarity_index(p));
2412        else {
2413                status[0] = p->status;
2414                status[1] = 0;
2415        }
2416        switch (p->status) {
2417        case DIFF_STATUS_COPIED:
2418        case DIFF_STATUS_RENAMED:
2419                two_paths = 1;
2420                break;
2421        case DIFF_STATUS_ADDED:
2422        case DIFF_STATUS_DELETED:
2423                two_paths = 0;
2424                break;
2425        default:
2426                two_paths = 0;
2427                break;
2428        }
2429        if (!(options->output_format & DIFF_FORMAT_NAME_STATUS)) {
2430                printf(":%06o %06o %s ",
2431                       p->one->mode, p->two->mode,
2432                       diff_unique_abbrev(p->one->sha1, abbrev));
2433                printf("%s ",
2434                       diff_unique_abbrev(p->two->sha1, abbrev));
2435        }
2436        printf("%s%c%s", status, inter_name_termination,
2437                        two_paths || p->one->mode ?  path_one : path_two);
2438        if (two_paths)
2439                printf("%c%s", inter_name_termination, path_two);
2440        putchar(line_termination);
2441        if (path_one != p->one->path)
2442                free((void*)path_one);
2443        if (path_two != p->two->path)
2444                free((void*)path_two);
2445}
2446
2447static void diff_flush_name(struct diff_filepair *p, struct diff_options *opt)
2448{
2449        char *path = p->two->path;
2450
2451        if (opt->line_termination)
2452                path = quote_one(p->two->path);
2453        printf("%s%c", path, opt->line_termination);
2454        if (p->two->path != path)
2455                free(path);
2456}
2457
2458int diff_unmodified_pair(struct diff_filepair *p)
2459{
2460        /* This function is written stricter than necessary to support
2461         * the currently implemented transformers, but the idea is to
2462         * let transformers to produce diff_filepairs any way they want,
2463         * and filter and clean them up here before producing the output.
2464         */
2465        struct diff_filespec *one, *two;
2466
2467        if (DIFF_PAIR_UNMERGED(p))
2468                return 0; /* unmerged is interesting */
2469
2470        one = p->one;
2471        two = p->two;
2472
2473        /* deletion, addition, mode or type change
2474         * and rename are all interesting.
2475         */
2476        if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
2477            DIFF_PAIR_MODE_CHANGED(p) ||
2478            strcmp(one->path, two->path))
2479                return 0;
2480
2481        /* both are valid and point at the same path.  that is, we are
2482         * dealing with a change.
2483         */
2484        if (one->sha1_valid && two->sha1_valid &&
2485            !hashcmp(one->sha1, two->sha1))
2486                return 1; /* no change */
2487        if (!one->sha1_valid && !two->sha1_valid)
2488                return 1; /* both look at the same file on the filesystem. */
2489        return 0;
2490}
2491
2492static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
2493{
2494        if (diff_unmodified_pair(p))
2495                return;
2496
2497        if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2498            (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2499                return; /* no tree diffs in patch format */
2500
2501        run_diff(p, o);
2502}
2503
2504static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
2505                            struct diffstat_t *diffstat)
2506{
2507        if (diff_unmodified_pair(p))
2508                return;
2509
2510        if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2511            (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2512                return; /* no tree diffs in patch format */
2513
2514        run_diffstat(p, o, diffstat);
2515}
2516
2517static void diff_flush_checkdiff(struct diff_filepair *p,
2518                struct diff_options *o)
2519{
2520        if (diff_unmodified_pair(p))
2521                return;
2522
2523        if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2524            (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2525                return; /* no tree diffs in patch format */
2526
2527        run_checkdiff(p, o);
2528}
2529
2530int diff_queue_is_empty(void)
2531{
2532        struct diff_queue_struct *q = &diff_queued_diff;
2533        int i;
2534        for (i = 0; i < q->nr; i++)
2535                if (!diff_unmodified_pair(q->queue[i]))
2536                        return 0;
2537        return 1;
2538}
2539
2540#if DIFF_DEBUG
2541void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
2542{
2543        fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
2544                x, one ? one : "",
2545                s->path,
2546                DIFF_FILE_VALID(s) ? "valid" : "invalid",
2547                s->mode,
2548                s->sha1_valid ? sha1_to_hex(s->sha1) : "");
2549        fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
2550                x, one ? one : "",
2551                s->size, s->xfrm_flags);
2552}
2553
2554void diff_debug_filepair(const struct diff_filepair *p, int i)
2555{
2556        diff_debug_filespec(p->one, i, "one");
2557        diff_debug_filespec(p->two, i, "two");
2558        fprintf(stderr, "score %d, status %c stays %d broken %d\n",
2559                p->score, p->status ? p->status : '?',
2560                p->source_stays, p->broken_pair);
2561}
2562
2563void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
2564{
2565        int i;
2566        if (msg)
2567                fprintf(stderr, "%s\n", msg);
2568        fprintf(stderr, "q->nr = %d\n", q->nr);
2569        for (i = 0; i < q->nr; i++) {
2570                struct diff_filepair *p = q->queue[i];
2571                diff_debug_filepair(p, i);
2572        }
2573}
2574#endif
2575
2576static void diff_resolve_rename_copy(void)
2577{
2578        int i, j;
2579        struct diff_filepair *p, *pp;
2580        struct diff_queue_struct *q = &diff_queued_diff;
2581
2582        diff_debug_queue("resolve-rename-copy", q);
2583
2584        for (i = 0; i < q->nr; i++) {
2585                p = q->queue[i];
2586                p->status = 0; /* undecided */
2587                if (DIFF_PAIR_UNMERGED(p))
2588                        p->status = DIFF_STATUS_UNMERGED;
2589                else if (!DIFF_FILE_VALID(p->one))
2590                        p->status = DIFF_STATUS_ADDED;
2591                else if (!DIFF_FILE_VALID(p->two))
2592                        p->status = DIFF_STATUS_DELETED;
2593                else if (DIFF_PAIR_TYPE_CHANGED(p))
2594                        p->status = DIFF_STATUS_TYPE_CHANGED;
2595
2596                /* from this point on, we are dealing with a pair
2597                 * whose both sides are valid and of the same type, i.e.
2598                 * either in-place edit or rename/copy edit.
2599                 */
2600                else if (DIFF_PAIR_RENAME(p)) {
2601                        if (p->source_stays) {
2602                                p->status = DIFF_STATUS_COPIED;
2603                                continue;
2604                        }
2605                        /* See if there is some other filepair that
2606                         * copies from the same source as us.  If so
2607                         * we are a copy.  Otherwise we are either a
2608                         * copy if the path stays, or a rename if it
2609                         * does not, but we already handled "stays" case.
2610                         */
2611                        for (j = i + 1; j < q->nr; j++) {
2612                                pp = q->queue[j];
2613                                if (strcmp(pp->one->path, p->one->path))
2614                                        continue; /* not us */
2615                                if (!DIFF_PAIR_RENAME(pp))
2616                                        continue; /* not a rename/copy */
2617                                /* pp is a rename/copy from the same source */
2618                                p->status = DIFF_STATUS_COPIED;
2619                                break;
2620                        }
2621                        if (!p->status)
2622                                p->status = DIFF_STATUS_RENAMED;
2623                }
2624                else if (hashcmp(p->one->sha1, p->two->sha1) ||
2625                         p->one->mode != p->two->mode ||
2626                         is_null_sha1(p->one->sha1))
2627                        p->status = DIFF_STATUS_MODIFIED;
2628                else {
2629                        /* This is a "no-change" entry and should not
2630                         * happen anymore, but prepare for broken callers.
2631                         */
2632                        error("feeding unmodified %s to diffcore",
2633                              p->one->path);
2634                        p->status = DIFF_STATUS_UNKNOWN;
2635                }
2636        }
2637        diff_debug_queue("resolve-rename-copy done", q);
2638}
2639
2640static int check_pair_status(struct diff_filepair *p)
2641{
2642        switch (p->status) {
2643        case DIFF_STATUS_UNKNOWN:
2644                return 0;
2645        case 0:
2646                die("internal error in diff-resolve-rename-copy");
2647        default:
2648                return 1;
2649        }
2650}
2651
2652static void flush_one_pair(struct diff_filepair *p, struct diff_options *opt)
2653{
2654        int fmt = opt->output_format;
2655
2656        if (fmt & DIFF_FORMAT_CHECKDIFF)
2657                diff_flush_checkdiff(p, opt);
2658        else if (fmt & (DIFF_FORMAT_RAW | DIFF_FORMAT_NAME_STATUS))
2659                diff_flush_raw(p, opt);
2660        else if (fmt & DIFF_FORMAT_NAME)
2661                diff_flush_name(p, opt);
2662}
2663
2664static void show_file_mode_name(const char *newdelete, struct diff_filespec *fs)
2665{
2666        char *name = quote_one(fs->path);
2667        if (fs->mode)
2668                printf(" %s mode %06o %s\n", newdelete, fs->mode, name);
2669        else
2670                printf(" %s %s\n", newdelete, name);
2671        free(name);
2672}
2673
2674
2675static void show_mode_change(struct diff_filepair *p, int show_name)
2676{
2677        if (p->one->mode && p->two->mode && p->one->mode != p->two->mode) {
2678                if (show_name) {
2679                        char *name = quote_one(p->two->path);
2680                        printf(" mode change %06o => %06o %s\n",
2681                               p->one->mode, p->two->mode, name);
2682                        free(name);
2683                }
2684                else
2685                        printf(" mode change %06o => %06o\n",
2686                               p->one->mode, p->two->mode);
2687        }
2688}
2689
2690static void show_rename_copy(const char *renamecopy, struct diff_filepair *p)
2691{
2692        char *names = pprint_rename(p->one->path, p->two->path);
2693
2694        printf(" %s %s (%d%%)\n", renamecopy, names, similarity_index(p));
2695        free(names);
2696        show_mode_change(p, 0);
2697}
2698
2699static void diff_summary(struct diff_filepair *p)
2700{
2701        switch(p->status) {
2702        case DIFF_STATUS_DELETED:
2703                show_file_mode_name("delete", p->one);
2704                break;
2705        case DIFF_STATUS_ADDED:
2706                show_file_mode_name("create", p->two);
2707                break;
2708        case DIFF_STATUS_COPIED:
2709                show_rename_copy("copy", p);
2710                break;
2711        case DIFF_STATUS_RENAMED:
2712                show_rename_copy("rename", p);
2713                break;
2714        default:
2715                if (p->score) {
2716                        char *name = quote_one(p->two->path);
2717                        printf(" rewrite %s (%d%%)\n", name,
2718                               similarity_index(p));
2719                        free(name);
2720                        show_mode_change(p, 0);
2721                } else  show_mode_change(p, 1);
2722                break;
2723        }
2724}
2725
2726struct patch_id_t {
2727        struct xdiff_emit_state xm;
2728        SHA_CTX *ctx;
2729        int patchlen;
2730};
2731
2732static int remove_space(char *line, int len)
2733{
2734        int i;
2735        char *dst = line;
2736        unsigned char c;
2737
2738        for (i = 0; i < len; i++)
2739                if (!isspace((c = line[i])))
2740                        *dst++ = c;
2741
2742        return dst - line;
2743}
2744
2745static void patch_id_consume(void *priv, char *line, unsigned long len)
2746{
2747        struct patch_id_t *data = priv;
2748        int new_len;
2749
2750        /* Ignore line numbers when computing the SHA1 of the patch */
2751        if (!prefixcmp(line, "@@ -"))
2752                return;
2753
2754        new_len = remove_space(line, len);
2755
2756        SHA1_Update(data->ctx, line, new_len);
2757        data->patchlen += new_len;
2758}
2759
2760/* returns 0 upon success, and writes result into sha1 */
2761static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1)
2762{
2763        struct diff_queue_struct *q = &diff_queued_diff;
2764        int i;
2765        SHA_CTX ctx;
2766        struct patch_id_t data;
2767        char buffer[PATH_MAX * 4 + 20];
2768
2769        SHA1_Init(&ctx);
2770        memset(&data, 0, sizeof(struct patch_id_t));
2771        data.ctx = &ctx;
2772        data.xm.consume = patch_id_consume;
2773
2774        for (i = 0; i < q->nr; i++) {
2775                xpparam_t xpp;
2776                xdemitconf_t xecfg;
2777                xdemitcb_t ecb;
2778                mmfile_t mf1, mf2;
2779                struct diff_filepair *p = q->queue[i];
2780                int len1, len2;
2781
2782                memset(&xecfg, 0, sizeof(xecfg));
2783                if (p->status == 0)
2784                        return error("internal diff status error");
2785                if (p->status == DIFF_STATUS_UNKNOWN)
2786                        continue;
2787                if (diff_unmodified_pair(p))
2788                        continue;
2789                if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
2790                    (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
2791                        continue;
2792                if (DIFF_PAIR_UNMERGED(p))
2793                        continue;
2794
2795                diff_fill_sha1_info(p->one);
2796                diff_fill_sha1_info(p->two);
2797                if (fill_mmfile(&mf1, p->one) < 0 ||
2798                                fill_mmfile(&mf2, p->two) < 0)
2799                        return error("unable to read files to diff");
2800
2801                /* Maybe hash p->two? into the patch id? */
2802                if (diff_filespec_is_binary(p->two))
2803                        continue;
2804
2805                len1 = remove_space(p->one->path, strlen(p->one->path));
2806                len2 = remove_space(p->two->path, strlen(p->two->path));
2807                if (p->one->mode == 0)
2808                        len1 = snprintf(buffer, sizeof(buffer),
2809                                        "diff--gita/%.*sb/%.*s"
2810                                        "newfilemode%06o"
2811                                        "---/dev/null"
2812                                        "+++b/%.*s",
2813                                        len1, p->one->path,
2814                                        len2, p->two->path,
2815                                        p->two->mode,
2816                                        len2, p->two->path);
2817                else if (p->two->mode == 0)
2818                        len1 = snprintf(buffer, sizeof(buffer),
2819                                        "diff--gita/%.*sb/%.*s"
2820                                        "deletedfilemode%06o"
2821                                        "---a/%.*s"
2822                                        "+++/dev/null",
2823                                        len1, p->one->path,
2824                                        len2, p->two->path,
2825                                        p->one->mode,
2826                                        len1, p->one->path);
2827                else
2828                        len1 = snprintf(buffer, sizeof(buffer),
2829                                        "diff--gita/%.*sb/%.*s"
2830                                        "---a/%.*s"
2831                                        "+++b/%.*s",
2832                                        len1, p->one->path,
2833                                        len2, p->two->path,
2834                                        len1, p->one->path,
2835                                        len2, p->two->path);
2836                SHA1_Update(&ctx, buffer, len1);
2837
2838                xpp.flags = XDF_NEED_MINIMAL;
2839                xecfg.ctxlen = 3;
2840                xecfg.flags = XDL_EMIT_FUNCNAMES;
2841                ecb.outf = xdiff_outf;
2842                ecb.priv = &data;
2843                xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
2844        }
2845
2846        SHA1_Final(sha1, &ctx);
2847        return 0;
2848}
2849
2850int diff_flush_patch_id(struct diff_options *options, unsigned char *sha1)
2851{
2852        struct diff_queue_struct *q = &diff_queued_diff;
2853        int i;
2854        int result = diff_get_patch_id(options, sha1);
2855
2856        for (i = 0; i < q->nr; i++)
2857                diff_free_filepair(q->queue[i]);
2858
2859        free(q->queue);
2860        q->queue = NULL;
2861        q->nr = q->alloc = 0;
2862
2863        return result;
2864}
2865
2866static int is_summary_empty(const struct diff_queue_struct *q)
2867{
2868        int i;
2869
2870        for (i = 0; i < q->nr; i++) {
2871                const struct diff_filepair *p = q->queue[i];
2872
2873                switch (p->status) {
2874                case DIFF_STATUS_DELETED:
2875                case DIFF_STATUS_ADDED:
2876                case DIFF_STATUS_COPIED:
2877                case DIFF_STATUS_RENAMED:
2878                        return 0;
2879                default:
2880                        if (p->score)
2881                                return 0;
2882                        if (p->one->mode && p->two->mode &&
2883                            p->one->mode != p->two->mode)
2884                                return 0;
2885                        break;
2886                }
2887        }
2888        return 1;
2889}
2890
2891void diff_flush(struct diff_options *options)
2892{
2893        struct diff_queue_struct *q = &diff_queued_diff;
2894        int i, output_format = options->output_format;
2895        int separator = 0;
2896
2897        /*
2898         * Order: raw, stat, summary, patch
2899         * or:    name/name-status/checkdiff (other bits clear)
2900         */
2901        if (!q->nr)
2902                goto free_queue;
2903
2904        if (output_format & (DIFF_FORMAT_RAW |
2905                             DIFF_FORMAT_NAME |
2906                             DIFF_FORMAT_NAME_STATUS |
2907                             DIFF_FORMAT_CHECKDIFF)) {
2908                for (i = 0; i < q->nr; i++) {
2909                        struct diff_filepair *p = q->queue[i];
2910                        if (check_pair_status(p))
2911                                flush_one_pair(p, options);
2912                }
2913                separator++;
2914        }
2915
2916        if (output_format & (DIFF_FORMAT_DIFFSTAT|DIFF_FORMAT_SHORTSTAT|DIFF_FORMAT_NUMSTAT)) {
2917                struct diffstat_t diffstat;
2918
2919                memset(&diffstat, 0, sizeof(struct diffstat_t));
2920                diffstat.xm.consume = diffstat_consume;
2921                for (i = 0; i < q->nr; i++) {
2922                        struct diff_filepair *p = q->queue[i];
2923                        if (check_pair_status(p))
2924                                diff_flush_stat(p, options, &diffstat);
2925                }
2926                if (output_format & DIFF_FORMAT_NUMSTAT)
2927                        show_numstat(&diffstat, options);
2928                if (output_format & DIFF_FORMAT_DIFFSTAT)
2929                        show_stats(&diffstat, options);
2930                else if (output_format & DIFF_FORMAT_SHORTSTAT)
2931                        show_shortstats(&diffstat);
2932                separator++;
2933        }
2934
2935        if (output_format & DIFF_FORMAT_SUMMARY && !is_summary_empty(q)) {
2936                for (i = 0; i < q->nr; i++)
2937                        diff_summary(q->queue[i]);
2938                separator++;
2939        }
2940
2941        if (output_format & DIFF_FORMAT_PATCH) {
2942                if (separator) {
2943                        if (options->stat_sep) {
2944                                /* attach patch instead of inline */
2945                                fputs(options->stat_sep, stdout);
2946                        } else {
2947                                putchar(options->line_termination);
2948                        }
2949                }
2950
2951                for (i = 0; i < q->nr; i++) {
2952                        struct diff_filepair *p = q->queue[i];
2953                        if (check_pair_status(p))
2954                                diff_flush_patch(p, options);
2955                }
2956        }
2957
2958        if (output_format & DIFF_FORMAT_CALLBACK)
2959                options->format_callback(q, options, options->format_callback_data);
2960
2961        for (i = 0; i < q->nr; i++)
2962                diff_free_filepair(q->queue[i]);
2963free_queue:
2964        free(q->queue);
2965        q->queue = NULL;
2966        q->nr = q->alloc = 0;
2967}
2968
2969static void diffcore_apply_filter(const char *filter)
2970{
2971        int i;
2972        struct diff_queue_struct *q = &diff_queued_diff;
2973        struct diff_queue_struct outq;
2974        outq.queue = NULL;
2975        outq.nr = outq.alloc = 0;
2976
2977        if (!filter)
2978                return;
2979
2980        if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
2981                int found;
2982                for (i = found = 0; !found && i < q->nr; i++) {
2983                        struct diff_filepair *p = q->queue[i];
2984                        if (((p->status == DIFF_STATUS_MODIFIED) &&
2985                             ((p->score &&
2986                               strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
2987                              (!p->score &&
2988                               strchr(filter, DIFF_STATUS_MODIFIED)))) ||
2989                            ((p->status != DIFF_STATUS_MODIFIED) &&
2990                             strchr(filter, p->status)))
2991                                found++;
2992                }
2993                if (found)
2994                        return;
2995
2996                /* otherwise we will clear the whole queue
2997                 * by copying the empty outq at the end of this
2998                 * function, but first clear the current entries
2999                 * in the queue.
3000                 */
3001                for (i = 0; i < q->nr; i++)
3002                        diff_free_filepair(q->queue[i]);
3003        }
3004        else {
3005                /* Only the matching ones */
3006                for (i = 0; i < q->nr; i++) {
3007                        struct diff_filepair *p = q->queue[i];
3008
3009                        if (((p->status == DIFF_STATUS_MODIFIED) &&
3010                             ((p->score &&
3011                               strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
3012                              (!p->score &&
3013                               strchr(filter, DIFF_STATUS_MODIFIED)))) ||
3014                            ((p->status != DIFF_STATUS_MODIFIED) &&
3015                             strchr(filter, p->status)))
3016                                diff_q(&outq, p);
3017                        else
3018                                diff_free_filepair(p);
3019                }
3020        }
3021        free(q->queue);
3022        *q = outq;
3023}
3024
3025void diffcore_std(struct diff_options *options)
3026{
3027        if (options->quiet)
3028                return;
3029
3030        if (options->break_opt != -1)
3031                diffcore_break(options->break_opt);
3032        if (options->detect_rename)
3033                diffcore_rename(options);
3034        if (options->break_opt != -1)
3035                diffcore_merge_broken();
3036        if (options->pickaxe)
3037                diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
3038        if (options->orderfile)
3039                diffcore_order(options->orderfile);
3040        diff_resolve_rename_copy();
3041        diffcore_apply_filter(options->filter);
3042
3043        options->has_changes = !!diff_queued_diff.nr;
3044}
3045
3046
3047void diff_addremove(struct diff_options *options,
3048                    int addremove, unsigned mode,
3049                    const unsigned char *sha1,
3050                    const char *base, const char *path)
3051{
3052        char concatpath[PATH_MAX];
3053        struct diff_filespec *one, *two;
3054
3055        /* This may look odd, but it is a preparation for
3056         * feeding "there are unchanged files which should
3057         * not produce diffs, but when you are doing copy
3058         * detection you would need them, so here they are"
3059         * entries to the diff-core.  They will be prefixed
3060         * with something like '=' or '*' (I haven't decided
3061         * which but should not make any difference).
3062         * Feeding the same new and old to diff_change()
3063         * also has the same effect.
3064         * Before the final output happens, they are pruned after
3065         * merged into rename/copy pairs as appropriate.
3066         */
3067        if (options->reverse_diff)
3068                addremove = (addremove == '+' ? '-' :
3069                             addremove == '-' ? '+' : addremove);
3070
3071        if (!path) path = "";
3072        sprintf(concatpath, "%s%s", base, path);
3073        one = alloc_filespec(concatpath);
3074        two = alloc_filespec(concatpath);
3075
3076        if (addremove != '+')
3077                fill_filespec(one, sha1, mode);
3078        if (addremove != '-')
3079                fill_filespec(two, sha1, mode);
3080
3081        diff_queue(&diff_queued_diff, one, two);
3082        options->has_changes = 1;
3083}
3084
3085void diff_change(struct diff_options *options,
3086                 unsigned old_mode, unsigned new_mode,
3087                 const unsigned char *old_sha1,
3088                 const unsigned char *new_sha1,
3089                 const char *base, const char *path)
3090{
3091        char concatpath[PATH_MAX];
3092        struct diff_filespec *one, *two;
3093
3094        if (options->reverse_diff) {
3095                unsigned tmp;
3096                const unsigned char *tmp_c;
3097                tmp = old_mode; old_mode = new_mode; new_mode = tmp;
3098                tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
3099        }
3100        if (!path) path = "";
3101        sprintf(concatpath, "%s%s", base, path);
3102        one = alloc_filespec(concatpath);
3103        two = alloc_filespec(concatpath);
3104        fill_filespec(one, old_sha1, old_mode);
3105        fill_filespec(two, new_sha1, new_mode);
3106
3107        diff_queue(&diff_queued_diff, one, two);
3108        options->has_changes = 1;
3109}
3110
3111void diff_unmerge(struct diff_options *options,
3112                  const char *path,
3113                  unsigned mode, const unsigned char *sha1)
3114{
3115        struct diff_filespec *one, *two;
3116        one = alloc_filespec(path);
3117        two = alloc_filespec(path);
3118        fill_filespec(one, sha1, mode);
3119        diff_queue(&diff_queued_diff, one, two)->is_unmerged = 1;
3120}