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