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