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