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