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