diff.con commit diff-files --stat: do not dump core with unmerged index. (cbdda02)
   1/*
   2 * Copyright (C) 2005 Junio C Hamano
   3 */
   4#include <sys/types.h>
   5#include <sys/wait.h>
   6#include <signal.h>
   7#include "cache.h"
   8#include "quote.h"
   9#include "diff.h"
  10#include "diffcore.h"
  11#include "xdiff-interface.h"
  12
  13static int use_size_cache;
  14
  15int diff_rename_limit_default = -1;
  16
  17int git_diff_config(const char *var, const char *value)
  18{
  19        if (!strcmp(var, "diff.renamelimit")) {
  20                diff_rename_limit_default = git_config_int(var, value);
  21                return 0;
  22        }
  23
  24        return git_default_config(var, value);
  25}
  26
  27static char *quote_one(const char *str)
  28{
  29        int needlen;
  30        char *xp;
  31
  32        if (!str)
  33                return NULL;
  34        needlen = quote_c_style(str, NULL, NULL, 0);
  35        if (!needlen)
  36                return strdup(str);
  37        xp = xmalloc(needlen + 1);
  38        quote_c_style(str, xp, NULL, 0);
  39        return xp;
  40}
  41
  42static char *quote_two(const char *one, const char *two)
  43{
  44        int need_one = quote_c_style(one, NULL, NULL, 1);
  45        int need_two = quote_c_style(two, NULL, NULL, 1);
  46        char *xp;
  47
  48        if (need_one + need_two) {
  49                if (!need_one) need_one = strlen(one);
  50                if (!need_two) need_one = strlen(two);
  51
  52                xp = xmalloc(need_one + need_two + 3);
  53                xp[0] = '"';
  54                quote_c_style(one, xp + 1, NULL, 1);
  55                quote_c_style(two, xp + need_one + 1, NULL, 1);
  56                strcpy(xp + need_one + need_two + 1, "\"");
  57                return xp;
  58        }
  59        need_one = strlen(one);
  60        need_two = strlen(two);
  61        xp = xmalloc(need_one + need_two + 1);
  62        strcpy(xp, one);
  63        strcpy(xp + need_one, two);
  64        return xp;
  65}
  66
  67static const char *external_diff(void)
  68{
  69        static const char *external_diff_cmd = NULL;
  70        static int done_preparing = 0;
  71
  72        if (done_preparing)
  73                return external_diff_cmd;
  74        external_diff_cmd = getenv("GIT_EXTERNAL_DIFF");
  75        done_preparing = 1;
  76        return external_diff_cmd;
  77}
  78
  79#define TEMPFILE_PATH_LEN               50
  80
  81static struct diff_tempfile {
  82        const char *name; /* filename external diff should read from */
  83        char hex[41];
  84        char mode[10];
  85        char tmp_path[TEMPFILE_PATH_LEN];
  86} diff_temp[2];
  87
  88static int count_lines(const char *data, int size)
  89{
  90        int count, ch, completely_empty = 1, nl_just_seen = 0;
  91        count = 0;
  92        while (0 < size--) {
  93                ch = *data++;
  94                if (ch == '\n') {
  95                        count++;
  96                        nl_just_seen = 1;
  97                        completely_empty = 0;
  98                }
  99                else {
 100                        nl_just_seen = 0;
 101                        completely_empty = 0;
 102                }
 103        }
 104        if (completely_empty)
 105                return 0;
 106        if (!nl_just_seen)
 107                count++; /* no trailing newline */
 108        return count;
 109}
 110
 111static void print_line_count(int count)
 112{
 113        switch (count) {
 114        case 0:
 115                printf("0,0");
 116                break;
 117        case 1:
 118                printf("1");
 119                break;
 120        default:
 121                printf("1,%d", count);
 122                break;
 123        }
 124}
 125
 126static void copy_file(int prefix, const char *data, int size)
 127{
 128        int ch, nl_just_seen = 1;
 129        while (0 < size--) {
 130                ch = *data++;
 131                if (nl_just_seen)
 132                        putchar(prefix);
 133                putchar(ch);
 134                if (ch == '\n')
 135                        nl_just_seen = 1;
 136                else
 137                        nl_just_seen = 0;
 138        }
 139        if (!nl_just_seen)
 140                printf("\n\\ No newline at end of file\n");
 141}
 142
 143static void emit_rewrite_diff(const char *name_a,
 144                              const char *name_b,
 145                              struct diff_filespec *one,
 146                              struct diff_filespec *two)
 147{
 148        int lc_a, lc_b;
 149        diff_populate_filespec(one, 0);
 150        diff_populate_filespec(two, 0);
 151        lc_a = count_lines(one->data, one->size);
 152        lc_b = count_lines(two->data, two->size);
 153        printf("--- %s\n+++ %s\n@@ -", name_a, name_b);
 154        print_line_count(lc_a);
 155        printf(" +");
 156        print_line_count(lc_b);
 157        printf(" @@\n");
 158        if (lc_a)
 159                copy_file('-', one->data, one->size);
 160        if (lc_b)
 161                copy_file('+', two->data, two->size);
 162}
 163
 164static int fill_mmfile(mmfile_t *mf, struct diff_filespec *one)
 165{
 166        if (!DIFF_FILE_VALID(one)) {
 167                mf->ptr = ""; /* does not matter */
 168                mf->size = 0;
 169                return 0;
 170        }
 171        else if (diff_populate_filespec(one, 0))
 172                return -1;
 173        mf->ptr = one->data;
 174        mf->size = one->size;
 175        return 0;
 176}
 177
 178struct emit_callback {
 179        const char **label_path;
 180};
 181
 182static int fn_out(void *priv, mmbuffer_t *mb, int nbuf)
 183{
 184        int i;
 185        struct emit_callback *ecbdata = priv;
 186
 187        if (ecbdata->label_path[0]) {
 188                printf("--- %s\n", ecbdata->label_path[0]);
 189                printf("+++ %s\n", ecbdata->label_path[1]);
 190                ecbdata->label_path[0] = ecbdata->label_path[1] = NULL;
 191        }
 192        for (i = 0; i < nbuf; i++)
 193                if (!fwrite(mb[i].ptr, mb[i].size, 1, stdout))
 194                        return -1;
 195        return 0;
 196}
 197
 198struct diffstat_t {
 199        struct xdiff_emit_state xm;
 200
 201        int nr;
 202        int alloc;
 203        struct diffstat_file {
 204                char *name;
 205                unsigned is_unmerged:1;
 206                unsigned is_binary:1;
 207                unsigned int added, deleted;
 208        } **files;
 209};
 210
 211static struct diffstat_file *diffstat_add(struct diffstat_t *diffstat,
 212                const char *name)
 213{
 214        struct diffstat_file *x;
 215        x = xcalloc(sizeof (*x), 1);
 216        if (diffstat->nr == diffstat->alloc) {
 217                diffstat->alloc = alloc_nr(diffstat->alloc);
 218                diffstat->files = xrealloc(diffstat->files,
 219                                diffstat->alloc * sizeof(x));
 220        }
 221        diffstat->files[diffstat->nr++] = x;
 222        x->name = strdup(name);
 223        return x;
 224}
 225
 226static void diffstat_consume(void *priv, char *line, unsigned long len)
 227{
 228        struct diffstat_t *diffstat = priv;
 229        struct diffstat_file *x = diffstat->files[diffstat->nr - 1];
 230
 231        if (line[0] == '+')
 232                x->added++;
 233        else if (line[0] == '-')
 234                x->deleted++;
 235}
 236
 237static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
 238static const char minuses[]= "----------------------------------------------------------------------";
 239
 240static void show_stats(struct diffstat_t* data)
 241{
 242        char *prefix = "";
 243        int i, len, add, del, total, adds = 0, dels = 0;
 244        int max, max_change = 0, max_len = 0;
 245        int total_files = data->nr;
 246
 247        if (data->nr == 0)
 248                return;
 249
 250        for (i = 0; i < data->nr; i++) {
 251                struct diffstat_file *file = data->files[i];
 252
 253                if (file->is_binary || file->is_unmerged)
 254                        continue;
 255                if (max_change < file->added + file->deleted)
 256                        max_change = file->added + file->deleted;
 257                len = strlen(file->name);
 258                if (max_len < len)
 259                        max_len = len;
 260        }
 261
 262        for (i = 0; i < data->nr; i++) {
 263                char *name = data->files[i]->name;
 264                int added = data->files[i]->added;
 265                int deleted = data->files[i]->deleted;
 266
 267                if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
 268                        char *qname = xmalloc(len + 1);
 269                        quote_c_style(name, qname, NULL, 0);
 270                        free(name);
 271                        data->files[i]->name = name = qname;
 272                }
 273
 274                /*
 275                 * "scale" the filename
 276                 */
 277                len = strlen(name);
 278                max = max_len;
 279                if (max > 50)
 280                        max = 50;
 281                if (len > max) {
 282                        char *slash;
 283                        prefix = "...";
 284                        max -= 3;
 285                        name += len - max;
 286                        slash = strchr(name, '/');
 287                        if (slash)
 288                                name = slash;
 289                }
 290                len = max;
 291
 292                /*
 293                 * scale the add/delete
 294                 */
 295                max = max_change;
 296                if (max + len > 70)
 297                        max = 70 - len;
 298
 299                if (data->files[i]->is_binary) {
 300                        printf(" %s%-*s |  Bin\n", prefix, len, name);
 301                        goto free_diffstat_file;
 302                }
 303                else if (data->files[i]->is_unmerged) {
 304                        printf(" %s%-*s |  Unmerged\n", prefix, len, name);
 305                        goto free_diffstat_file;
 306                }
 307                else if (added + deleted == 0) {
 308                        total_files--;
 309                        goto free_diffstat_file;
 310                }
 311
 312                add = added;
 313                del = deleted;
 314                total = add + del;
 315                adds += add;
 316                dels += del;
 317
 318                if (max_change > 0) {
 319                        total = (total * max + max_change / 2) / max_change;
 320                        add = (add * max + max_change / 2) / max_change;
 321                        del = total - add;
 322                }
 323                printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
 324                                len, name, added + deleted,
 325                                add, pluses, del, minuses);
 326        free_diffstat_file:
 327                free(data->files[i]->name);
 328                free(data->files[i]);
 329        }
 330        free(data->files);
 331        printf(" %d files changed, %d insertions(+), %d deletions(-)\n",
 332                        total_files, adds, dels);
 333}
 334
 335#define FIRST_FEW_BYTES 8000
 336static int mmfile_is_binary(mmfile_t *mf)
 337{
 338        long sz = mf->size;
 339        if (FIRST_FEW_BYTES < sz)
 340                sz = FIRST_FEW_BYTES;
 341        if (memchr(mf->ptr, 0, sz))
 342                return 1;
 343        return 0;
 344}
 345
 346static void builtin_diff(const char *name_a,
 347                         const char *name_b,
 348                         struct diff_filespec *one,
 349                         struct diff_filespec *two,
 350                         const char *xfrm_msg,
 351                         int complete_rewrite)
 352{
 353        mmfile_t mf1, mf2;
 354        const char *lbl[2];
 355        char *a_one, *b_two;
 356
 357        a_one = quote_two("a/", name_a);
 358        b_two = quote_two("b/", name_b);
 359        lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null";
 360        lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null";
 361        printf("diff --git %s %s\n", a_one, b_two);
 362        if (lbl[0][0] == '/') {
 363                /* /dev/null */
 364                printf("new file mode %06o\n", two->mode);
 365                if (xfrm_msg && xfrm_msg[0])
 366                        puts(xfrm_msg);
 367        }
 368        else if (lbl[1][0] == '/') {
 369                printf("deleted file mode %06o\n", one->mode);
 370                if (xfrm_msg && xfrm_msg[0])
 371                        puts(xfrm_msg);
 372        }
 373        else {
 374                if (one->mode != two->mode) {
 375                        printf("old mode %06o\n", one->mode);
 376                        printf("new mode %06o\n", two->mode);
 377                }
 378                if (xfrm_msg && xfrm_msg[0])
 379                        puts(xfrm_msg);
 380                /*
 381                 * we do not run diff between different kind
 382                 * of objects.
 383                 */
 384                if ((one->mode ^ two->mode) & S_IFMT)
 385                        goto free_ab_and_return;
 386                if (complete_rewrite) {
 387                        emit_rewrite_diff(name_a, name_b, one, two);
 388                        goto free_ab_and_return;
 389                }
 390        }
 391
 392        if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
 393                die("unable to read files to diff");
 394
 395        if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
 396                printf("Binary files %s and %s differ\n", lbl[0], lbl[1]);
 397        else {
 398                /* Crazy xdl interfaces.. */
 399                const char *diffopts = getenv("GIT_DIFF_OPTS");
 400                xpparam_t xpp;
 401                xdemitconf_t xecfg;
 402                xdemitcb_t ecb;
 403                struct emit_callback ecbdata;
 404
 405                ecbdata.label_path = lbl;
 406                xpp.flags = XDF_NEED_MINIMAL;
 407                xecfg.ctxlen = 3;
 408                xecfg.flags = XDL_EMIT_FUNCNAMES;
 409                if (!diffopts)
 410                        ;
 411                else if (!strncmp(diffopts, "--unified=", 10))
 412                        xecfg.ctxlen = strtoul(diffopts + 10, NULL, 10);
 413                else if (!strncmp(diffopts, "-u", 2))
 414                        xecfg.ctxlen = strtoul(diffopts + 2, NULL, 10);
 415                ecb.outf = fn_out;
 416                ecb.priv = &ecbdata;
 417                xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
 418        }
 419
 420 free_ab_and_return:
 421        free(a_one);
 422        free(b_two);
 423        return;
 424}
 425
 426static void builtin_diffstat(const char *name_a, const char *name_b,
 427                struct diff_filespec *one, struct diff_filespec *two,
 428                struct diffstat_t *diffstat)
 429{
 430        mmfile_t mf1, mf2;
 431        struct diffstat_file *data;
 432
 433        data = diffstat_add(diffstat, name_a ? name_a : name_b);
 434
 435        if (!one || !two) {
 436                data->is_unmerged = 1;
 437                return;
 438        }
 439
 440        if (fill_mmfile(&mf1, one) < 0 || fill_mmfile(&mf2, two) < 0)
 441                die("unable to read files to diff");
 442
 443        if (mmfile_is_binary(&mf1) || mmfile_is_binary(&mf2))
 444                data->is_binary = 1;
 445        else {
 446                /* Crazy xdl interfaces.. */
 447                xpparam_t xpp;
 448                xdemitconf_t xecfg;
 449                xdemitcb_t ecb;
 450
 451                xpp.flags = XDF_NEED_MINIMAL;
 452                xecfg.ctxlen = 0;
 453                xecfg.flags = 0;
 454                ecb.outf = xdiff_outf;
 455                ecb.priv = diffstat;
 456                xdl_diff(&mf1, &mf2, &xpp, &xecfg, &ecb);
 457        }
 458}
 459
 460struct diff_filespec *alloc_filespec(const char *path)
 461{
 462        int namelen = strlen(path);
 463        struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
 464
 465        memset(spec, 0, sizeof(*spec));
 466        spec->path = (char *)(spec + 1);
 467        memcpy(spec->path, path, namelen+1);
 468        return spec;
 469}
 470
 471void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
 472                   unsigned short mode)
 473{
 474        if (mode) {
 475                spec->mode = canon_mode(mode);
 476                memcpy(spec->sha1, sha1, 20);
 477                spec->sha1_valid = !!memcmp(sha1, null_sha1, 20);
 478        }
 479}
 480
 481/*
 482 * Given a name and sha1 pair, if the dircache tells us the file in
 483 * the work tree has that object contents, return true, so that
 484 * prepare_temp_file() does not have to inflate and extract.
 485 */
 486static int work_tree_matches(const char *name, const unsigned char *sha1)
 487{
 488        struct cache_entry *ce;
 489        struct stat st;
 490        int pos, len;
 491
 492        /* We do not read the cache ourselves here, because the
 493         * benchmark with my previous version that always reads cache
 494         * shows that it makes things worse for diff-tree comparing
 495         * two linux-2.6 kernel trees in an already checked out work
 496         * tree.  This is because most diff-tree comparisons deal with
 497         * only a small number of files, while reading the cache is
 498         * expensive for a large project, and its cost outweighs the
 499         * savings we get by not inflating the object to a temporary
 500         * file.  Practically, this code only helps when we are used
 501         * by diff-cache --cached, which does read the cache before
 502         * calling us.
 503         */
 504        if (!active_cache)
 505                return 0;
 506
 507        len = strlen(name);
 508        pos = cache_name_pos(name, len);
 509        if (pos < 0)
 510                return 0;
 511        ce = active_cache[pos];
 512        if ((lstat(name, &st) < 0) ||
 513            !S_ISREG(st.st_mode) || /* careful! */
 514            ce_match_stat(ce, &st, 0) ||
 515            memcmp(sha1, ce->sha1, 20))
 516                return 0;
 517        /* we return 1 only when we can stat, it is a regular file,
 518         * stat information matches, and sha1 recorded in the cache
 519         * matches.  I.e. we know the file in the work tree really is
 520         * the same as the <name, sha1> pair.
 521         */
 522        return 1;
 523}
 524
 525static struct sha1_size_cache {
 526        unsigned char sha1[20];
 527        unsigned long size;
 528} **sha1_size_cache;
 529static int sha1_size_cache_nr, sha1_size_cache_alloc;
 530
 531static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
 532                                                 int find_only,
 533                                                 unsigned long size)
 534{
 535        int first, last;
 536        struct sha1_size_cache *e;
 537
 538        first = 0;
 539        last = sha1_size_cache_nr;
 540        while (last > first) {
 541                int cmp, next = (last + first) >> 1;
 542                e = sha1_size_cache[next];
 543                cmp = memcmp(e->sha1, sha1, 20);
 544                if (!cmp)
 545                        return e;
 546                if (cmp < 0) {
 547                        last = next;
 548                        continue;
 549                }
 550                first = next+1;
 551        }
 552        /* not found */
 553        if (find_only)
 554                return NULL;
 555        /* insert to make it at "first" */
 556        if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
 557                sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
 558                sha1_size_cache = xrealloc(sha1_size_cache,
 559                                           sha1_size_cache_alloc *
 560                                           sizeof(*sha1_size_cache));
 561        }
 562        sha1_size_cache_nr++;
 563        if (first < sha1_size_cache_nr)
 564                memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
 565                        (sha1_size_cache_nr - first - 1) *
 566                        sizeof(*sha1_size_cache));
 567        e = xmalloc(sizeof(struct sha1_size_cache));
 568        sha1_size_cache[first] = e;
 569        memcpy(e->sha1, sha1, 20);
 570        e->size = size;
 571        return e;
 572}
 573
 574/*
 575 * While doing rename detection and pickaxe operation, we may need to
 576 * grab the data for the blob (or file) for our own in-core comparison.
 577 * diff_filespec has data and size fields for this purpose.
 578 */
 579int diff_populate_filespec(struct diff_filespec *s, int size_only)
 580{
 581        int err = 0;
 582        if (!DIFF_FILE_VALID(s))
 583                die("internal error: asking to populate invalid file.");
 584        if (S_ISDIR(s->mode))
 585                return -1;
 586
 587        if (!use_size_cache)
 588                size_only = 0;
 589
 590        if (s->data)
 591                return err;
 592        if (!s->sha1_valid ||
 593            work_tree_matches(s->path, s->sha1)) {
 594                struct stat st;
 595                int fd;
 596                if (lstat(s->path, &st) < 0) {
 597                        if (errno == ENOENT) {
 598                        err_empty:
 599                                err = -1;
 600                        empty:
 601                                s->data = "";
 602                                s->size = 0;
 603                                return err;
 604                        }
 605                }
 606                s->size = st.st_size;
 607                if (!s->size)
 608                        goto empty;
 609                if (size_only)
 610                        return 0;
 611                if (S_ISLNK(st.st_mode)) {
 612                        int ret;
 613                        s->data = xmalloc(s->size);
 614                        s->should_free = 1;
 615                        ret = readlink(s->path, s->data, s->size);
 616                        if (ret < 0) {
 617                                free(s->data);
 618                                goto err_empty;
 619                        }
 620                        return 0;
 621                }
 622                fd = open(s->path, O_RDONLY);
 623                if (fd < 0)
 624                        goto err_empty;
 625                s->data = mmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
 626                close(fd);
 627                if (s->data == MAP_FAILED)
 628                        goto err_empty;
 629                s->should_munmap = 1;
 630        }
 631        else {
 632                char type[20];
 633                struct sha1_size_cache *e;
 634
 635                if (size_only) {
 636                        e = locate_size_cache(s->sha1, 1, 0);
 637                        if (e) {
 638                                s->size = e->size;
 639                                return 0;
 640                        }
 641                        if (!sha1_object_info(s->sha1, type, &s->size))
 642                                locate_size_cache(s->sha1, 0, s->size);
 643                }
 644                else {
 645                        s->data = read_sha1_file(s->sha1, type, &s->size);
 646                        s->should_free = 1;
 647                }
 648        }
 649        return 0;
 650}
 651
 652void diff_free_filespec_data(struct diff_filespec *s)
 653{
 654        if (s->should_free)
 655                free(s->data);
 656        else if (s->should_munmap)
 657                munmap(s->data, s->size);
 658        s->should_free = s->should_munmap = 0;
 659        s->data = NULL;
 660        free(s->cnt_data);
 661        s->cnt_data = NULL;
 662}
 663
 664static void prep_temp_blob(struct diff_tempfile *temp,
 665                           void *blob,
 666                           unsigned long size,
 667                           const unsigned char *sha1,
 668                           int mode)
 669{
 670        int fd;
 671
 672        fd = git_mkstemp(temp->tmp_path, TEMPFILE_PATH_LEN, ".diff_XXXXXX");
 673        if (fd < 0)
 674                die("unable to create temp-file");
 675        if (write(fd, blob, size) != size)
 676                die("unable to write temp-file");
 677        close(fd);
 678        temp->name = temp->tmp_path;
 679        strcpy(temp->hex, sha1_to_hex(sha1));
 680        temp->hex[40] = 0;
 681        sprintf(temp->mode, "%06o", mode);
 682}
 683
 684static void prepare_temp_file(const char *name,
 685                              struct diff_tempfile *temp,
 686                              struct diff_filespec *one)
 687{
 688        if (!DIFF_FILE_VALID(one)) {
 689        not_a_valid_file:
 690                /* A '-' entry produces this for file-2, and
 691                 * a '+' entry produces this for file-1.
 692                 */
 693                temp->name = "/dev/null";
 694                strcpy(temp->hex, ".");
 695                strcpy(temp->mode, ".");
 696                return;
 697        }
 698
 699        if (!one->sha1_valid ||
 700            work_tree_matches(name, one->sha1)) {
 701                struct stat st;
 702                if (lstat(name, &st) < 0) {
 703                        if (errno == ENOENT)
 704                                goto not_a_valid_file;
 705                        die("stat(%s): %s", name, strerror(errno));
 706                }
 707                if (S_ISLNK(st.st_mode)) {
 708                        int ret;
 709                        char buf[PATH_MAX + 1]; /* ought to be SYMLINK_MAX */
 710                        if (sizeof(buf) <= st.st_size)
 711                                die("symlink too long: %s", name);
 712                        ret = readlink(name, buf, st.st_size);
 713                        if (ret < 0)
 714                                die("readlink(%s)", name);
 715                        prep_temp_blob(temp, buf, st.st_size,
 716                                       (one->sha1_valid ?
 717                                        one->sha1 : null_sha1),
 718                                       (one->sha1_valid ?
 719                                        one->mode : S_IFLNK));
 720                }
 721                else {
 722                        /* we can borrow from the file in the work tree */
 723                        temp->name = name;
 724                        if (!one->sha1_valid)
 725                                strcpy(temp->hex, sha1_to_hex(null_sha1));
 726                        else
 727                                strcpy(temp->hex, sha1_to_hex(one->sha1));
 728                        /* Even though we may sometimes borrow the
 729                         * contents from the work tree, we always want
 730                         * one->mode.  mode is trustworthy even when
 731                         * !(one->sha1_valid), as long as
 732                         * DIFF_FILE_VALID(one).
 733                         */
 734                        sprintf(temp->mode, "%06o", one->mode);
 735                }
 736                return;
 737        }
 738        else {
 739                if (diff_populate_filespec(one, 0))
 740                        die("cannot read data blob for %s", one->path);
 741                prep_temp_blob(temp, one->data, one->size,
 742                               one->sha1, one->mode);
 743        }
 744}
 745
 746static void remove_tempfile(void)
 747{
 748        int i;
 749
 750        for (i = 0; i < 2; i++)
 751                if (diff_temp[i].name == diff_temp[i].tmp_path) {
 752                        unlink(diff_temp[i].name);
 753                        diff_temp[i].name = NULL;
 754                }
 755}
 756
 757static void remove_tempfile_on_signal(int signo)
 758{
 759        remove_tempfile();
 760        signal(SIGINT, SIG_DFL);
 761        raise(signo);
 762}
 763
 764static int spawn_prog(const char *pgm, const char **arg)
 765{
 766        pid_t pid;
 767        int status;
 768
 769        fflush(NULL);
 770        pid = fork();
 771        if (pid < 0)
 772                die("unable to fork");
 773        if (!pid) {
 774                execvp(pgm, (char *const*) arg);
 775                exit(255);
 776        }
 777
 778        while (waitpid(pid, &status, 0) < 0) {
 779                if (errno == EINTR)
 780                        continue;
 781                return -1;
 782        }
 783
 784        /* Earlier we did not check the exit status because
 785         * diff exits non-zero if files are different, and
 786         * we are not interested in knowing that.  It was a
 787         * mistake which made it harder to quit a diff-*
 788         * session that uses the git-apply-patch-script as
 789         * the GIT_EXTERNAL_DIFF.  A custom GIT_EXTERNAL_DIFF
 790         * should also exit non-zero only when it wants to
 791         * abort the entire diff-* session.
 792         */
 793        if (WIFEXITED(status) && !WEXITSTATUS(status))
 794                return 0;
 795        return -1;
 796}
 797
 798/* An external diff command takes:
 799 *
 800 * diff-cmd name infile1 infile1-sha1 infile1-mode \
 801 *               infile2 infile2-sha1 infile2-mode [ rename-to ]
 802 *
 803 */
 804static void run_external_diff(const char *pgm,
 805                              const char *name,
 806                              const char *other,
 807                              struct diff_filespec *one,
 808                              struct diff_filespec *two,
 809                              const char *xfrm_msg,
 810                              int complete_rewrite)
 811{
 812        const char *spawn_arg[10];
 813        struct diff_tempfile *temp = diff_temp;
 814        int retval;
 815        static int atexit_asked = 0;
 816        const char *othername;
 817        const char **arg = &spawn_arg[0];
 818
 819        othername = (other? other : name);
 820        if (one && two) {
 821                prepare_temp_file(name, &temp[0], one);
 822                prepare_temp_file(othername, &temp[1], two);
 823                if (! atexit_asked &&
 824                    (temp[0].name == temp[0].tmp_path ||
 825                     temp[1].name == temp[1].tmp_path)) {
 826                        atexit_asked = 1;
 827                        atexit(remove_tempfile);
 828                }
 829                signal(SIGINT, remove_tempfile_on_signal);
 830        }
 831
 832        if (one && two) {
 833                *arg++ = pgm;
 834                *arg++ = name;
 835                *arg++ = temp[0].name;
 836                *arg++ = temp[0].hex;
 837                *arg++ = temp[0].mode;
 838                *arg++ = temp[1].name;
 839                *arg++ = temp[1].hex;
 840                *arg++ = temp[1].mode;
 841                if (other) {
 842                        *arg++ = other;
 843                        *arg++ = xfrm_msg;
 844                }
 845        } else {
 846                *arg++ = pgm;
 847                *arg++ = name;
 848        }
 849        *arg = NULL;
 850        retval = spawn_prog(pgm, spawn_arg);
 851        remove_tempfile();
 852        if (retval) {
 853                fprintf(stderr, "external diff died, stopping at %s.\n", name);
 854                exit(1);
 855        }
 856}
 857
 858static void run_diff_cmd(const char *pgm,
 859                         const char *name,
 860                         const char *other,
 861                         struct diff_filespec *one,
 862                         struct diff_filespec *two,
 863                         const char *xfrm_msg,
 864                         int complete_rewrite)
 865{
 866        if (pgm) {
 867                run_external_diff(pgm, name, other, one, two, xfrm_msg,
 868                                  complete_rewrite);
 869                return;
 870        }
 871        if (one && two)
 872                builtin_diff(name, other ? other : name,
 873                             one, two, xfrm_msg, complete_rewrite);
 874        else
 875                printf("* Unmerged path %s\n", name);
 876}
 877
 878static void diff_fill_sha1_info(struct diff_filespec *one)
 879{
 880        if (DIFF_FILE_VALID(one)) {
 881                if (!one->sha1_valid) {
 882                        struct stat st;
 883                        if (lstat(one->path, &st) < 0)
 884                                die("stat %s", one->path);
 885                        if (index_path(one->sha1, one->path, &st, 0))
 886                                die("cannot hash %s\n", one->path);
 887                }
 888        }
 889        else
 890                memset(one->sha1, 0, 20);
 891}
 892
 893static void run_diff(struct diff_filepair *p, struct diff_options *o)
 894{
 895        const char *pgm = external_diff();
 896        char msg[PATH_MAX*2+300], *xfrm_msg;
 897        struct diff_filespec *one;
 898        struct diff_filespec *two;
 899        const char *name;
 900        const char *other;
 901        char *name_munged, *other_munged;
 902        int complete_rewrite = 0;
 903        int len;
 904
 905        if (DIFF_PAIR_UNMERGED(p)) {
 906                /* unmerged */
 907                run_diff_cmd(pgm, p->one->path, NULL, NULL, NULL, NULL, 0);
 908                return;
 909        }
 910
 911        name = p->one->path;
 912        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
 913        name_munged = quote_one(name);
 914        other_munged = quote_one(other);
 915        one = p->one; two = p->two;
 916
 917        diff_fill_sha1_info(one);
 918        diff_fill_sha1_info(two);
 919
 920        len = 0;
 921        switch (p->status) {
 922        case DIFF_STATUS_COPIED:
 923                len += snprintf(msg + len, sizeof(msg) - len,
 924                                "similarity index %d%%\n"
 925                                "copy from %s\n"
 926                                "copy to %s\n",
 927                                (int)(0.5 + p->score * 100.0/MAX_SCORE),
 928                                name_munged, other_munged);
 929                break;
 930        case DIFF_STATUS_RENAMED:
 931                len += snprintf(msg + len, sizeof(msg) - len,
 932                                "similarity index %d%%\n"
 933                                "rename from %s\n"
 934                                "rename to %s\n",
 935                                (int)(0.5 + p->score * 100.0/MAX_SCORE),
 936                                name_munged, other_munged);
 937                break;
 938        case DIFF_STATUS_MODIFIED:
 939                if (p->score) {
 940                        len += snprintf(msg + len, sizeof(msg) - len,
 941                                        "dissimilarity index %d%%\n",
 942                                        (int)(0.5 + p->score *
 943                                              100.0/MAX_SCORE));
 944                        complete_rewrite = 1;
 945                        break;
 946                }
 947                /* fallthru */
 948        default:
 949                /* nothing */
 950                ;
 951        }
 952
 953        if (memcmp(one->sha1, two->sha1, 20)) {
 954                char one_sha1[41];
 955                int abbrev = o->full_index ? 40 : DEFAULT_ABBREV;
 956                memcpy(one_sha1, sha1_to_hex(one->sha1), 41);
 957
 958                len += snprintf(msg + len, sizeof(msg) - len,
 959                                "index %.*s..%.*s",
 960                                abbrev, one_sha1, abbrev,
 961                                sha1_to_hex(two->sha1));
 962                if (one->mode == two->mode)
 963                        len += snprintf(msg + len, sizeof(msg) - len,
 964                                        " %06o", one->mode);
 965                len += snprintf(msg + len, sizeof(msg) - len, "\n");
 966        }
 967
 968        if (len)
 969                msg[--len] = 0;
 970        xfrm_msg = len ? msg : NULL;
 971
 972        if (!pgm &&
 973            DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
 974            (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
 975                /* a filepair that changes between file and symlink
 976                 * needs to be split into deletion and creation.
 977                 */
 978                struct diff_filespec *null = alloc_filespec(two->path);
 979                run_diff_cmd(NULL, name, other, one, null, xfrm_msg, 0);
 980                free(null);
 981                null = alloc_filespec(one->path);
 982                run_diff_cmd(NULL, name, other, null, two, xfrm_msg, 0);
 983                free(null);
 984        }
 985        else
 986                run_diff_cmd(pgm, name, other, one, two, xfrm_msg,
 987                             complete_rewrite);
 988
 989        free(name_munged);
 990        free(other_munged);
 991}
 992
 993static void run_diffstat(struct diff_filepair *p, struct diff_options *o,
 994                struct diffstat_t *diffstat)
 995{
 996        const char *name;
 997        const char *other;
 998
 999        if (DIFF_PAIR_UNMERGED(p)) {
1000                /* unmerged */
1001                builtin_diffstat(p->one->path, NULL, NULL, NULL, diffstat);
1002                return;
1003        }
1004
1005        name = p->one->path;
1006        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
1007
1008        diff_fill_sha1_info(p->one);
1009        diff_fill_sha1_info(p->two);
1010
1011        builtin_diffstat(name, other, p->one, p->two, diffstat);
1012}
1013
1014void diff_setup(struct diff_options *options)
1015{
1016        memset(options, 0, sizeof(*options));
1017        options->output_format = DIFF_FORMAT_RAW;
1018        options->line_termination = '\n';
1019        options->break_opt = -1;
1020        options->rename_limit = -1;
1021
1022        options->change = diff_change;
1023        options->add_remove = diff_addremove;
1024}
1025
1026int diff_setup_done(struct diff_options *options)
1027{
1028        if ((options->find_copies_harder &&
1029             options->detect_rename != DIFF_DETECT_COPY) ||
1030            (0 <= options->rename_limit && !options->detect_rename))
1031                return -1;
1032        if (options->detect_rename && options->rename_limit < 0)
1033                options->rename_limit = diff_rename_limit_default;
1034        if (options->setup & DIFF_SETUP_USE_CACHE) {
1035                if (!active_cache)
1036                        /* read-cache does not die even when it fails
1037                         * so it is safe for us to do this here.  Also
1038                         * it does not smudge active_cache or active_nr
1039                         * when it fails, so we do not have to worry about
1040                         * cleaning it up ourselves either.
1041                         */
1042                        read_cache();
1043        }
1044        if (options->setup & DIFF_SETUP_USE_SIZE_CACHE)
1045                use_size_cache = 1;
1046        if (options->abbrev <= 0 || 40 < options->abbrev)
1047                options->abbrev = 40; /* full */
1048
1049        return 0;
1050}
1051
1052int diff_opt_parse(struct diff_options *options, const char **av, int ac)
1053{
1054        const char *arg = av[0];
1055        if (!strcmp(arg, "-p") || !strcmp(arg, "-u"))
1056                options->output_format = DIFF_FORMAT_PATCH;
1057        else if (!strcmp(arg, "--patch-with-raw")) {
1058                options->output_format = DIFF_FORMAT_PATCH;
1059                options->with_raw = 1;
1060        }
1061        else if (!strcmp(arg, "--stat"))
1062                options->output_format = DIFF_FORMAT_DIFFSTAT;
1063        else if (!strcmp(arg, "-z"))
1064                options->line_termination = 0;
1065        else if (!strncmp(arg, "-l", 2))
1066                options->rename_limit = strtoul(arg+2, NULL, 10);
1067        else if (!strcmp(arg, "--full-index"))
1068                options->full_index = 1;
1069        else if (!strcmp(arg, "--name-only"))
1070                options->output_format = DIFF_FORMAT_NAME;
1071        else if (!strcmp(arg, "--name-status"))
1072                options->output_format = DIFF_FORMAT_NAME_STATUS;
1073        else if (!strcmp(arg, "-R"))
1074                options->reverse_diff = 1;
1075        else if (!strncmp(arg, "-S", 2))
1076                options->pickaxe = arg + 2;
1077        else if (!strcmp(arg, "-s"))
1078                options->output_format = DIFF_FORMAT_NO_OUTPUT;
1079        else if (!strncmp(arg, "-O", 2))
1080                options->orderfile = arg + 2;
1081        else if (!strncmp(arg, "--diff-filter=", 14))
1082                options->filter = arg + 14;
1083        else if (!strcmp(arg, "--pickaxe-all"))
1084                options->pickaxe_opts = DIFF_PICKAXE_ALL;
1085        else if (!strcmp(arg, "--pickaxe-regex"))
1086                options->pickaxe_opts = DIFF_PICKAXE_REGEX;
1087        else if (!strncmp(arg, "-B", 2)) {
1088                if ((options->break_opt =
1089                     diff_scoreopt_parse(arg)) == -1)
1090                        return -1;
1091        }
1092        else if (!strncmp(arg, "-M", 2)) {
1093                if ((options->rename_score =
1094                     diff_scoreopt_parse(arg)) == -1)
1095                        return -1;
1096                options->detect_rename = DIFF_DETECT_RENAME;
1097        }
1098        else if (!strncmp(arg, "-C", 2)) {
1099                if ((options->rename_score =
1100                     diff_scoreopt_parse(arg)) == -1)
1101                        return -1;
1102                options->detect_rename = DIFF_DETECT_COPY;
1103        }
1104        else if (!strcmp(arg, "--find-copies-harder"))
1105                options->find_copies_harder = 1;
1106        else if (!strcmp(arg, "--abbrev"))
1107                options->abbrev = DEFAULT_ABBREV;
1108        else if (!strncmp(arg, "--abbrev=", 9)) {
1109                options->abbrev = strtoul(arg + 9, NULL, 10);
1110                if (options->abbrev < MINIMUM_ABBREV)
1111                        options->abbrev = MINIMUM_ABBREV;
1112                else if (40 < options->abbrev)
1113                        options->abbrev = 40;
1114        }
1115        else
1116                return 0;
1117        return 1;
1118}
1119
1120static int parse_num(const char **cp_p)
1121{
1122        unsigned long num, scale;
1123        int ch, dot;
1124        const char *cp = *cp_p;
1125
1126        num = 0;
1127        scale = 1;
1128        dot = 0;
1129        for(;;) {
1130                ch = *cp;
1131                if ( !dot && ch == '.' ) {
1132                        scale = 1;
1133                        dot = 1;
1134                } else if ( ch == '%' ) {
1135                        scale = dot ? scale*100 : 100;
1136                        cp++;   /* % is always at the end */
1137                        break;
1138                } else if ( ch >= '0' && ch <= '9' ) {
1139                        if ( scale < 100000 ) {
1140                                scale *= 10;
1141                                num = (num*10) + (ch-'0');
1142                        }
1143                } else {
1144                        break;
1145                }
1146                cp++;
1147        }
1148        *cp_p = cp;
1149
1150        /* user says num divided by scale and we say internally that
1151         * is MAX_SCORE * num / scale.
1152         */
1153        return (num >= scale) ? MAX_SCORE : (MAX_SCORE * num / scale);
1154}
1155
1156int diff_scoreopt_parse(const char *opt)
1157{
1158        int opt1, opt2, cmd;
1159
1160        if (*opt++ != '-')
1161                return -1;
1162        cmd = *opt++;
1163        if (cmd != 'M' && cmd != 'C' && cmd != 'B')
1164                return -1; /* that is not a -M, -C nor -B option */
1165
1166        opt1 = parse_num(&opt);
1167        if (cmd != 'B')
1168                opt2 = 0;
1169        else {
1170                if (*opt == 0)
1171                        opt2 = 0;
1172                else if (*opt != '/')
1173                        return -1; /* we expect -B80/99 or -B80 */
1174                else {
1175                        opt++;
1176                        opt2 = parse_num(&opt);
1177                }
1178        }
1179        if (*opt != 0)
1180                return -1;
1181        return opt1 | (opt2 << 16);
1182}
1183
1184struct diff_queue_struct diff_queued_diff;
1185
1186void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
1187{
1188        if (queue->alloc <= queue->nr) {
1189                queue->alloc = alloc_nr(queue->alloc);
1190                queue->queue = xrealloc(queue->queue,
1191                                        sizeof(dp) * queue->alloc);
1192        }
1193        queue->queue[queue->nr++] = dp;
1194}
1195
1196struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
1197                                 struct diff_filespec *one,
1198                                 struct diff_filespec *two)
1199{
1200        struct diff_filepair *dp = xmalloc(sizeof(*dp));
1201        dp->one = one;
1202        dp->two = two;
1203        dp->score = 0;
1204        dp->status = 0;
1205        dp->source_stays = 0;
1206        dp->broken_pair = 0;
1207        if (queue)
1208                diff_q(queue, dp);
1209        return dp;
1210}
1211
1212void diff_free_filepair(struct diff_filepair *p)
1213{
1214        diff_free_filespec_data(p->one);
1215        diff_free_filespec_data(p->two);
1216        free(p->one);
1217        free(p->two);
1218        free(p);
1219}
1220
1221/* This is different from find_unique_abbrev() in that
1222 * it stuffs the result with dots for alignment.
1223 */
1224const char *diff_unique_abbrev(const unsigned char *sha1, int len)
1225{
1226        int abblen;
1227        const char *abbrev;
1228        if (len == 40)
1229                return sha1_to_hex(sha1);
1230
1231        abbrev = find_unique_abbrev(sha1, len);
1232        if (!abbrev)
1233                return sha1_to_hex(sha1);
1234        abblen = strlen(abbrev);
1235        if (abblen < 37) {
1236                static char hex[41];
1237                if (len < abblen && abblen <= len + 2)
1238                        sprintf(hex, "%s%.*s", abbrev, len+3-abblen, "..");
1239                else
1240                        sprintf(hex, "%s...", abbrev);
1241                return hex;
1242        }
1243        return sha1_to_hex(sha1);
1244}
1245
1246static void diff_flush_raw(struct diff_filepair *p,
1247                           int line_termination,
1248                           int inter_name_termination,
1249                           struct diff_options *options,
1250                           int output_format)
1251{
1252        int two_paths;
1253        char status[10];
1254        int abbrev = options->abbrev;
1255        const char *path_one, *path_two;
1256
1257        path_one = p->one->path;
1258        path_two = p->two->path;
1259        if (line_termination) {
1260                path_one = quote_one(path_one);
1261                path_two = quote_one(path_two);
1262        }
1263
1264        if (p->score)
1265                sprintf(status, "%c%03d", p->status,
1266                        (int)(0.5 + p->score * 100.0/MAX_SCORE));
1267        else {
1268                status[0] = p->status;
1269                status[1] = 0;
1270        }
1271        switch (p->status) {
1272        case DIFF_STATUS_COPIED:
1273        case DIFF_STATUS_RENAMED:
1274                two_paths = 1;
1275                break;
1276        case DIFF_STATUS_ADDED:
1277        case DIFF_STATUS_DELETED:
1278                two_paths = 0;
1279                break;
1280        default:
1281                two_paths = 0;
1282                break;
1283        }
1284        if (output_format != DIFF_FORMAT_NAME_STATUS) {
1285                printf(":%06o %06o %s ",
1286                       p->one->mode, p->two->mode,
1287                       diff_unique_abbrev(p->one->sha1, abbrev));
1288                printf("%s ",
1289                       diff_unique_abbrev(p->two->sha1, abbrev));
1290        }
1291        printf("%s%c%s", status, inter_name_termination, path_one);
1292        if (two_paths)
1293                printf("%c%s", inter_name_termination, path_two);
1294        putchar(line_termination);
1295        if (path_one != p->one->path)
1296                free((void*)path_one);
1297        if (path_two != p->two->path)
1298                free((void*)path_two);
1299}
1300
1301static void diff_flush_name(struct diff_filepair *p,
1302                            int inter_name_termination,
1303                            int line_termination)
1304{
1305        char *path = p->two->path;
1306
1307        if (line_termination)
1308                path = quote_one(p->two->path);
1309        else
1310                path = p->two->path;
1311        printf("%s%c", path, line_termination);
1312        if (p->two->path != path)
1313                free(path);
1314}
1315
1316int diff_unmodified_pair(struct diff_filepair *p)
1317{
1318        /* This function is written stricter than necessary to support
1319         * the currently implemented transformers, but the idea is to
1320         * let transformers to produce diff_filepairs any way they want,
1321         * and filter and clean them up here before producing the output.
1322         */
1323        struct diff_filespec *one, *two;
1324
1325        if (DIFF_PAIR_UNMERGED(p))
1326                return 0; /* unmerged is interesting */
1327
1328        one = p->one;
1329        two = p->two;
1330
1331        /* deletion, addition, mode or type change
1332         * and rename are all interesting.
1333         */
1334        if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
1335            DIFF_PAIR_MODE_CHANGED(p) ||
1336            strcmp(one->path, two->path))
1337                return 0;
1338
1339        /* both are valid and point at the same path.  that is, we are
1340         * dealing with a change.
1341         */
1342        if (one->sha1_valid && two->sha1_valid &&
1343            !memcmp(one->sha1, two->sha1, sizeof(one->sha1)))
1344                return 1; /* no change */
1345        if (!one->sha1_valid && !two->sha1_valid)
1346                return 1; /* both look at the same file on the filesystem. */
1347        return 0;
1348}
1349
1350static void diff_flush_patch(struct diff_filepair *p, struct diff_options *o)
1351{
1352        if (diff_unmodified_pair(p))
1353                return;
1354
1355        if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1356            (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1357                return; /* no tree diffs in patch format */
1358
1359        run_diff(p, o);
1360}
1361
1362static void diff_flush_stat(struct diff_filepair *p, struct diff_options *o,
1363                struct diffstat_t *diffstat)
1364{
1365        if (diff_unmodified_pair(p))
1366                return;
1367
1368        if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
1369            (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
1370                return; /* no tree diffs in patch format */
1371
1372        run_diffstat(p, o, diffstat);
1373}
1374
1375int diff_queue_is_empty(void)
1376{
1377        struct diff_queue_struct *q = &diff_queued_diff;
1378        int i;
1379        for (i = 0; i < q->nr; i++)
1380                if (!diff_unmodified_pair(q->queue[i]))
1381                        return 0;
1382        return 1;
1383}
1384
1385#if DIFF_DEBUG
1386void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
1387{
1388        fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
1389                x, one ? one : "",
1390                s->path,
1391                DIFF_FILE_VALID(s) ? "valid" : "invalid",
1392                s->mode,
1393                s->sha1_valid ? sha1_to_hex(s->sha1) : "");
1394        fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
1395                x, one ? one : "",
1396                s->size, s->xfrm_flags);
1397}
1398
1399void diff_debug_filepair(const struct diff_filepair *p, int i)
1400{
1401        diff_debug_filespec(p->one, i, "one");
1402        diff_debug_filespec(p->two, i, "two");
1403        fprintf(stderr, "score %d, status %c stays %d broken %d\n",
1404                p->score, p->status ? p->status : '?',
1405                p->source_stays, p->broken_pair);
1406}
1407
1408void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
1409{
1410        int i;
1411        if (msg)
1412                fprintf(stderr, "%s\n", msg);
1413        fprintf(stderr, "q->nr = %d\n", q->nr);
1414        for (i = 0; i < q->nr; i++) {
1415                struct diff_filepair *p = q->queue[i];
1416                diff_debug_filepair(p, i);
1417        }
1418}
1419#endif
1420
1421static void diff_resolve_rename_copy(void)
1422{
1423        int i, j;
1424        struct diff_filepair *p, *pp;
1425        struct diff_queue_struct *q = &diff_queued_diff;
1426
1427        diff_debug_queue("resolve-rename-copy", q);
1428
1429        for (i = 0; i < q->nr; i++) {
1430                p = q->queue[i];
1431                p->status = 0; /* undecided */
1432                if (DIFF_PAIR_UNMERGED(p))
1433                        p->status = DIFF_STATUS_UNMERGED;
1434                else if (!DIFF_FILE_VALID(p->one))
1435                        p->status = DIFF_STATUS_ADDED;
1436                else if (!DIFF_FILE_VALID(p->two))
1437                        p->status = DIFF_STATUS_DELETED;
1438                else if (DIFF_PAIR_TYPE_CHANGED(p))
1439                        p->status = DIFF_STATUS_TYPE_CHANGED;
1440
1441                /* from this point on, we are dealing with a pair
1442                 * whose both sides are valid and of the same type, i.e.
1443                 * either in-place edit or rename/copy edit.
1444                 */
1445                else if (DIFF_PAIR_RENAME(p)) {
1446                        if (p->source_stays) {
1447                                p->status = DIFF_STATUS_COPIED;
1448                                continue;
1449                        }
1450                        /* See if there is some other filepair that
1451                         * copies from the same source as us.  If so
1452                         * we are a copy.  Otherwise we are either a
1453                         * copy if the path stays, or a rename if it
1454                         * does not, but we already handled "stays" case.
1455                         */
1456                        for (j = i + 1; j < q->nr; j++) {
1457                                pp = q->queue[j];
1458                                if (strcmp(pp->one->path, p->one->path))
1459                                        continue; /* not us */
1460                                if (!DIFF_PAIR_RENAME(pp))
1461                                        continue; /* not a rename/copy */
1462                                /* pp is a rename/copy from the same source */
1463                                p->status = DIFF_STATUS_COPIED;
1464                                break;
1465                        }
1466                        if (!p->status)
1467                                p->status = DIFF_STATUS_RENAMED;
1468                }
1469                else if (memcmp(p->one->sha1, p->two->sha1, 20) ||
1470                         p->one->mode != p->two->mode)
1471                        p->status = DIFF_STATUS_MODIFIED;
1472                else {
1473                        /* This is a "no-change" entry and should not
1474                         * happen anymore, but prepare for broken callers.
1475                         */
1476                        error("feeding unmodified %s to diffcore",
1477                              p->one->path);
1478                        p->status = DIFF_STATUS_UNKNOWN;
1479                }
1480        }
1481        diff_debug_queue("resolve-rename-copy done", q);
1482}
1483
1484static void flush_one_pair(struct diff_filepair *p,
1485                           int diff_output_format,
1486                           struct diff_options *options,
1487                           struct diffstat_t *diffstat)
1488{
1489        int inter_name_termination = '\t';
1490        int line_termination = options->line_termination;
1491        if (!line_termination)
1492                inter_name_termination = 0;
1493
1494        switch (p->status) {
1495        case DIFF_STATUS_UNKNOWN:
1496                break;
1497        case 0:
1498                die("internal error in diff-resolve-rename-copy");
1499                break;
1500        default:
1501                switch (diff_output_format) {
1502                case DIFF_FORMAT_DIFFSTAT:
1503                        diff_flush_stat(p, options, diffstat);
1504                        break;
1505                case DIFF_FORMAT_PATCH:
1506                        diff_flush_patch(p, options);
1507                        break;
1508                case DIFF_FORMAT_RAW:
1509                case DIFF_FORMAT_NAME_STATUS:
1510                        diff_flush_raw(p, line_termination,
1511                                       inter_name_termination,
1512                                       options, diff_output_format);
1513                        break;
1514                case DIFF_FORMAT_NAME:
1515                        diff_flush_name(p,
1516                                        inter_name_termination,
1517                                        line_termination);
1518                        break;
1519                case DIFF_FORMAT_NO_OUTPUT:
1520                        break;
1521                }
1522        }
1523}
1524
1525void diff_flush(struct diff_options *options)
1526{
1527        struct diff_queue_struct *q = &diff_queued_diff;
1528        int i;
1529        int diff_output_format = options->output_format;
1530        struct diffstat_t *diffstat = NULL;
1531
1532        if (diff_output_format == DIFF_FORMAT_DIFFSTAT) {
1533                diffstat = xcalloc(sizeof (struct diffstat_t), 1);
1534                diffstat->xm.consume = diffstat_consume;
1535        }
1536
1537        if (options->with_raw) {
1538                for (i = 0; i < q->nr; i++) {
1539                        struct diff_filepair *p = q->queue[i];
1540                        flush_one_pair(p, DIFF_FORMAT_RAW, options, NULL);
1541                }
1542                putchar(options->line_termination);
1543        }
1544        for (i = 0; i < q->nr; i++) {
1545                struct diff_filepair *p = q->queue[i];
1546                flush_one_pair(p, diff_output_format, options, diffstat);
1547                diff_free_filepair(p);
1548        }
1549
1550        if (diffstat) {
1551                show_stats(diffstat);
1552                free(diffstat);
1553        }
1554
1555        free(q->queue);
1556        q->queue = NULL;
1557        q->nr = q->alloc = 0;
1558}
1559
1560static void diffcore_apply_filter(const char *filter)
1561{
1562        int i;
1563        struct diff_queue_struct *q = &diff_queued_diff;
1564        struct diff_queue_struct outq;
1565        outq.queue = NULL;
1566        outq.nr = outq.alloc = 0;
1567
1568        if (!filter)
1569                return;
1570
1571        if (strchr(filter, DIFF_STATUS_FILTER_AON)) {
1572                int found;
1573                for (i = found = 0; !found && i < q->nr; i++) {
1574                        struct diff_filepair *p = q->queue[i];
1575                        if (((p->status == DIFF_STATUS_MODIFIED) &&
1576                             ((p->score &&
1577                               strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
1578                              (!p->score &&
1579                               strchr(filter, DIFF_STATUS_MODIFIED)))) ||
1580                            ((p->status != DIFF_STATUS_MODIFIED) &&
1581                             strchr(filter, p->status)))
1582                                found++;
1583                }
1584                if (found)
1585                        return;
1586
1587                /* otherwise we will clear the whole queue
1588                 * by copying the empty outq at the end of this
1589                 * function, but first clear the current entries
1590                 * in the queue.
1591                 */
1592                for (i = 0; i < q->nr; i++)
1593                        diff_free_filepair(q->queue[i]);
1594        }
1595        else {
1596                /* Only the matching ones */
1597                for (i = 0; i < q->nr; i++) {
1598                        struct diff_filepair *p = q->queue[i];
1599
1600                        if (((p->status == DIFF_STATUS_MODIFIED) &&
1601                             ((p->score &&
1602                               strchr(filter, DIFF_STATUS_FILTER_BROKEN)) ||
1603                              (!p->score &&
1604                               strchr(filter, DIFF_STATUS_MODIFIED)))) ||
1605                            ((p->status != DIFF_STATUS_MODIFIED) &&
1606                             strchr(filter, p->status)))
1607                                diff_q(&outq, p);
1608                        else
1609                                diff_free_filepair(p);
1610                }
1611        }
1612        free(q->queue);
1613        *q = outq;
1614}
1615
1616void diffcore_std(struct diff_options *options)
1617{
1618        if (options->break_opt != -1)
1619                diffcore_break(options->break_opt);
1620        if (options->detect_rename)
1621                diffcore_rename(options);
1622        if (options->break_opt != -1)
1623                diffcore_merge_broken();
1624        if (options->pickaxe)
1625                diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
1626        if (options->orderfile)
1627                diffcore_order(options->orderfile);
1628        diff_resolve_rename_copy();
1629        diffcore_apply_filter(options->filter);
1630}
1631
1632
1633void diffcore_std_no_resolve(struct diff_options *options)
1634{
1635        if (options->pickaxe)
1636                diffcore_pickaxe(options->pickaxe, options->pickaxe_opts);
1637        if (options->orderfile)
1638                diffcore_order(options->orderfile);
1639        diffcore_apply_filter(options->filter);
1640}
1641
1642void diff_addremove(struct diff_options *options,
1643                    int addremove, unsigned mode,
1644                    const unsigned char *sha1,
1645                    const char *base, const char *path)
1646{
1647        char concatpath[PATH_MAX];
1648        struct diff_filespec *one, *two;
1649
1650        /* This may look odd, but it is a preparation for
1651         * feeding "there are unchanged files which should
1652         * not produce diffs, but when you are doing copy
1653         * detection you would need them, so here they are"
1654         * entries to the diff-core.  They will be prefixed
1655         * with something like '=' or '*' (I haven't decided
1656         * which but should not make any difference).
1657         * Feeding the same new and old to diff_change() 
1658         * also has the same effect.
1659         * Before the final output happens, they are pruned after
1660         * merged into rename/copy pairs as appropriate.
1661         */
1662        if (options->reverse_diff)
1663                addremove = (addremove == '+' ? '-' :
1664                             addremove == '-' ? '+' : addremove);
1665
1666        if (!path) path = "";
1667        sprintf(concatpath, "%s%s", base, path);
1668        one = alloc_filespec(concatpath);
1669        two = alloc_filespec(concatpath);
1670
1671        if (addremove != '+')
1672                fill_filespec(one, sha1, mode);
1673        if (addremove != '-')
1674                fill_filespec(two, sha1, mode);
1675
1676        diff_queue(&diff_queued_diff, one, two);
1677}
1678
1679void diff_change(struct diff_options *options,
1680                 unsigned old_mode, unsigned new_mode,
1681                 const unsigned char *old_sha1,
1682                 const unsigned char *new_sha1,
1683                 const char *base, const char *path) 
1684{
1685        char concatpath[PATH_MAX];
1686        struct diff_filespec *one, *two;
1687
1688        if (options->reverse_diff) {
1689                unsigned tmp;
1690                const unsigned char *tmp_c;
1691                tmp = old_mode; old_mode = new_mode; new_mode = tmp;
1692                tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
1693        }
1694        if (!path) path = "";
1695        sprintf(concatpath, "%s%s", base, path);
1696        one = alloc_filespec(concatpath);
1697        two = alloc_filespec(concatpath);
1698        fill_filespec(one, old_sha1, old_mode);
1699        fill_filespec(two, new_sha1, new_mode);
1700
1701        diff_queue(&diff_queued_diff, one, two);
1702}
1703
1704void diff_unmerge(struct diff_options *options,
1705                  const char *path)
1706{
1707        struct diff_filespec *one, *two;
1708        one = alloc_filespec(path);
1709        two = alloc_filespec(path);
1710        diff_queue(&diff_queued_diff, one, two);
1711}