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