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