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