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