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