diff.con commit git-read-tree: simplify merge loops enormously (d723c69)
   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 "diff.h"
   9#include "diffcore.h"
  10
  11static const char *diff_opts = "-pu";
  12static unsigned char null_sha1[20] = { 0, };
  13
  14static int reverse_diff;
  15static int use_size_cache;
  16
  17static const char *external_diff(void)
  18{
  19        static const char *external_diff_cmd = NULL;
  20        static int done_preparing = 0;
  21
  22        if (done_preparing)
  23                return external_diff_cmd;
  24
  25        /*
  26         * Default values above are meant to match the
  27         * Linux kernel development style.  Examples of
  28         * alternative styles you can specify via environment
  29         * variables are:
  30         *
  31         * GIT_DIFF_OPTS="-c";
  32         */
  33        if (gitenv("GIT_EXTERNAL_DIFF"))
  34                external_diff_cmd = gitenv("GIT_EXTERNAL_DIFF");
  35
  36        /* In case external diff fails... */
  37        diff_opts = gitenv("GIT_DIFF_OPTS") ? : diff_opts;
  38
  39        done_preparing = 1;
  40        return external_diff_cmd;
  41}
  42
  43/* Help to copy the thing properly quoted for the shell safety.
  44 * any single quote is replaced with '\'', and the caller is
  45 * expected to enclose the result within a single quote pair.
  46 *
  47 * E.g.
  48 *  original     sq_expand     result
  49 *  name     ==> name      ==> 'name'
  50 *  a b      ==> a b       ==> 'a b'
  51 *  a'b      ==> a'\''b    ==> 'a'\''b'
  52 */
  53static char *sq_expand(const char *src)
  54{
  55        static char *buf = NULL;
  56        int cnt, c;
  57        const char *cp;
  58        char *bp;
  59
  60        /* count bytes needed to store the quoted string. */
  61        for (cnt = 1, cp = src; *cp; cnt++, cp++)
  62                if (*cp == '\'')
  63                        cnt += 3;
  64
  65        buf = xmalloc(cnt);
  66        bp = buf;
  67        while ((c = *src++)) {
  68                if (c != '\'')
  69                        *bp++ = c;
  70                else {
  71                        bp = strcpy(bp, "'\\''");
  72                        bp += 4;
  73                }
  74        }
  75        *bp = 0;
  76        return buf;
  77}
  78
  79static struct diff_tempfile {
  80        const char *name; /* filename external diff should read from */
  81        char hex[41];
  82        char mode[10];
  83        char tmp_path[50];
  84} diff_temp[2];
  85
  86static void builtin_diff(const char *name_a,
  87                         const char *name_b,
  88                         struct diff_tempfile *temp,
  89                         const char *xfrm_msg)
  90{
  91        int i, next_at, cmd_size;
  92        const char *diff_cmd = "diff -L'%s%s' -L'%s%s'";
  93        const char *diff_arg  = "'%s' '%s'||:"; /* "||:" is to return 0 */
  94        const char *input_name_sq[2];
  95        const char *path0[2];
  96        const char *path1[2];
  97        const char *name_sq[2];
  98        char *cmd;
  99
 100        name_sq[0] = sq_expand(name_a);
 101        name_sq[1] = sq_expand(name_b);
 102
 103        /* diff_cmd and diff_arg have 6 %s in total which makes
 104         * the sum of these strings 12 bytes larger than required.
 105         * we use 2 spaces around diff-opts, and we need to count
 106         * terminating NUL, so we subtract 9 here.
 107         */
 108        cmd_size = (strlen(diff_cmd) + strlen(diff_opts) +
 109                        strlen(diff_arg) - 9);
 110        for (i = 0; i < 2; i++) {
 111                input_name_sq[i] = sq_expand(temp[i].name);
 112                if (!strcmp(temp[i].name, "/dev/null")) {
 113                        path0[i] = "/dev/null";
 114                        path1[i] = "";
 115                } else {
 116                        path0[i] = i ? "b/" : "a/";
 117                        path1[i] = name_sq[i];
 118                }
 119                cmd_size += (strlen(path0[i]) + strlen(path1[i]) +
 120                             strlen(input_name_sq[i]));
 121        }
 122
 123        cmd = xmalloc(cmd_size);
 124
 125        next_at = 0;
 126        next_at += snprintf(cmd+next_at, cmd_size-next_at,
 127                            diff_cmd,
 128                            path0[0], path1[0], path0[1], path1[1]);
 129        next_at += snprintf(cmd+next_at, cmd_size-next_at,
 130                            " %s ", diff_opts);
 131        next_at += snprintf(cmd+next_at, cmd_size-next_at,
 132                            diff_arg, input_name_sq[0], input_name_sq[1]);
 133
 134        printf("diff --git a/%s b/%s\n", name_a, name_b);
 135        if (!path1[0][0]) {
 136                printf("new file mode %s\n", temp[1].mode);
 137                if (xfrm_msg && xfrm_msg[0])
 138                        puts(xfrm_msg);
 139        }
 140        else if (!path1[1][0]) {
 141                printf("deleted file mode %s\n", temp[0].mode);
 142                if (xfrm_msg && xfrm_msg[0])
 143                        puts(xfrm_msg);
 144        }
 145        else {
 146                if (strcmp(temp[0].mode, temp[1].mode)) {
 147                        printf("old mode %s\n", temp[0].mode);
 148                        printf("new mode %s\n", temp[1].mode);
 149                }
 150                if (xfrm_msg && xfrm_msg[0])
 151                        puts(xfrm_msg);
 152
 153                if (strncmp(temp[0].mode, temp[1].mode, 3))
 154                        /* we do not run diff between different kind
 155                         * of objects.
 156                         */
 157                        exit(0);
 158        }
 159        fflush(NULL);
 160        execlp("/bin/sh","sh", "-c", cmd, NULL);
 161}
 162
 163struct diff_filespec *alloc_filespec(const char *path)
 164{
 165        int namelen = strlen(path);
 166        struct diff_filespec *spec = xmalloc(sizeof(*spec) + namelen + 1);
 167        spec->path = (char *)(spec + 1);
 168        strcpy(spec->path, path);
 169        spec->should_free = spec->should_munmap = 0;
 170        spec->xfrm_flags = 0;
 171        spec->size = 0;
 172        spec->data = NULL;
 173        spec->mode = 0;
 174        memset(spec->sha1, 0, 20);
 175        return spec;
 176}
 177
 178void fill_filespec(struct diff_filespec *spec, const unsigned char *sha1,
 179                   unsigned short mode)
 180{
 181        if (mode) {
 182                spec->mode = DIFF_FILE_CANON_MODE(mode);
 183                memcpy(spec->sha1, sha1, 20);
 184                spec->sha1_valid = !!memcmp(sha1, null_sha1, 20);
 185        }
 186}
 187
 188/*
 189 * Given a name and sha1 pair, if the dircache tells us the file in
 190 * the work tree has that object contents, return true, so that
 191 * prepare_temp_file() does not have to inflate and extract.
 192 */
 193static int work_tree_matches(const char *name, const unsigned char *sha1)
 194{
 195        struct cache_entry *ce;
 196        struct stat st;
 197        int pos, len;
 198
 199        /* We do not read the cache ourselves here, because the
 200         * benchmark with my previous version that always reads cache
 201         * shows that it makes things worse for diff-tree comparing
 202         * two linux-2.6 kernel trees in an already checked out work
 203         * tree.  This is because most diff-tree comparisons deal with
 204         * only a small number of files, while reading the cache is
 205         * expensive for a large project, and its cost outweighs the
 206         * savings we get by not inflating the object to a temporary
 207         * file.  Practically, this code only helps when we are used
 208         * by diff-cache --cached, which does read the cache before
 209         * calling us.
 210         */
 211        if (!active_cache)
 212                return 0;
 213
 214        len = strlen(name);
 215        pos = cache_name_pos(name, len);
 216        if (pos < 0)
 217                return 0;
 218        ce = active_cache[pos];
 219        if ((lstat(name, &st) < 0) ||
 220            !S_ISREG(st.st_mode) || /* careful! */
 221            ce_match_stat(ce, &st) ||
 222            memcmp(sha1, ce->sha1, 20))
 223                return 0;
 224        /* we return 1 only when we can stat, it is a regular file,
 225         * stat information matches, and sha1 recorded in the cache
 226         * matches.  I.e. we know the file in the work tree really is
 227         * the same as the <name, sha1> pair.
 228         */
 229        return 1;
 230}
 231
 232static struct sha1_size_cache {
 233        unsigned char sha1[20];
 234        unsigned long size;
 235} **sha1_size_cache;
 236static int sha1_size_cache_nr, sha1_size_cache_alloc;
 237
 238static struct sha1_size_cache *locate_size_cache(unsigned char *sha1,
 239                                                 int find_only,
 240                                                 unsigned long size)
 241{
 242        int first, last;
 243        struct sha1_size_cache *e;
 244
 245        first = 0;
 246        last = sha1_size_cache_nr;
 247        while (last > first) {
 248                int cmp, next = (last + first) >> 1;
 249                e = sha1_size_cache[next];
 250                cmp = memcmp(e->sha1, sha1, 20);
 251                if (!cmp)
 252                        return e;
 253                if (cmp < 0) {
 254                        last = next;
 255                        continue;
 256                }
 257                first = next+1;
 258        }
 259        /* not found */
 260        if (find_only)
 261                return NULL;
 262        /* insert to make it at "first" */
 263        if (sha1_size_cache_alloc <= sha1_size_cache_nr) {
 264                sha1_size_cache_alloc = alloc_nr(sha1_size_cache_alloc);
 265                sha1_size_cache = xrealloc(sha1_size_cache,
 266                                           sha1_size_cache_alloc *
 267                                           sizeof(*sha1_size_cache));
 268        }
 269        sha1_size_cache_nr++;
 270        if (first < sha1_size_cache_nr)
 271                memmove(sha1_size_cache + first + 1, sha1_size_cache + first,
 272                        (sha1_size_cache_nr - first - 1) *
 273                        sizeof(*sha1_size_cache));
 274        e = xmalloc(sizeof(struct sha1_size_cache));
 275        sha1_size_cache[first] = e;
 276        memcpy(e->sha1, sha1, 20);
 277        e->size = size;
 278        return e;
 279}
 280
 281/*
 282 * While doing rename detection and pickaxe operation, we may need to
 283 * grab the data for the blob (or file) for our own in-core comparison.
 284 * diff_filespec has data and size fields for this purpose.
 285 */
 286int diff_populate_filespec(struct diff_filespec *s, int size_only)
 287{
 288        int err = 0;
 289        if (!DIFF_FILE_VALID(s))
 290                die("internal error: asking to populate invalid file.");
 291        if (S_ISDIR(s->mode))
 292                return -1;
 293
 294        if (!use_size_cache)
 295                size_only = 0;
 296
 297        if (s->data)
 298                return err;
 299        if (!s->sha1_valid ||
 300            work_tree_matches(s->path, s->sha1)) {
 301                struct stat st;
 302                int fd;
 303                if (lstat(s->path, &st) < 0) {
 304                        if (errno == ENOENT) {
 305                        err_empty:
 306                                err = -1;
 307                        empty:
 308                                s->data = "";
 309                                s->size = 0;
 310                                return err;
 311                        }
 312                }
 313                s->size = st.st_size;
 314                if (!s->size)
 315                        goto empty;
 316                if (size_only)
 317                        return 0;
 318                if (S_ISLNK(st.st_mode)) {
 319                        int ret;
 320                        s->data = xmalloc(s->size);
 321                        s->should_free = 1;
 322                        ret = readlink(s->path, s->data, s->size);
 323                        if (ret < 0) {
 324                                free(s->data);
 325                                goto err_empty;
 326                        }
 327                        return 0;
 328                }
 329                fd = open(s->path, O_RDONLY);
 330                if (fd < 0)
 331                        goto err_empty;
 332                s->data = mmap(NULL, s->size, PROT_READ, MAP_PRIVATE, fd, 0);
 333                s->should_munmap = 1;
 334                close(fd);
 335        }
 336        else {
 337                char type[20];
 338                struct sha1_size_cache *e;
 339
 340                if (size_only) {
 341                        e = locate_size_cache(s->sha1, 1, 0);
 342                        if (e) {
 343                                s->size = e->size;
 344                                return 0;
 345                        }
 346                        if (!sha1_file_size(s->sha1, &s->size))
 347                                locate_size_cache(s->sha1, 0, s->size);
 348                }
 349                else {
 350                        s->data = read_sha1_file(s->sha1, type, &s->size);
 351                        s->should_free = 1;
 352                }
 353        }
 354        return 0;
 355}
 356
 357void diff_free_filespec_data(struct diff_filespec *s)
 358{
 359        if (s->should_free)
 360                free(s->data);
 361        else if (s->should_munmap)
 362                munmap(s->data, s->size);
 363        s->should_free = s->should_munmap = 0;
 364        s->data = NULL;
 365}
 366
 367static void prep_temp_blob(struct diff_tempfile *temp,
 368                           void *blob,
 369                           unsigned long size,
 370                           unsigned char *sha1,
 371                           int mode)
 372{
 373        int fd;
 374
 375        strcpy(temp->tmp_path, ".diff_XXXXXX");
 376        fd = mkstemp(temp->tmp_path);
 377        if (fd < 0)
 378                die("unable to create temp-file");
 379        if (write(fd, blob, size) != size)
 380                die("unable to write temp-file");
 381        close(fd);
 382        temp->name = temp->tmp_path;
 383        strcpy(temp->hex, sha1_to_hex(sha1));
 384        temp->hex[40] = 0;
 385        sprintf(temp->mode, "%06o", mode);
 386}
 387
 388static void prepare_temp_file(const char *name,
 389                              struct diff_tempfile *temp,
 390                              struct diff_filespec *one)
 391{
 392        if (!DIFF_FILE_VALID(one)) {
 393        not_a_valid_file:
 394                /* A '-' entry produces this for file-2, and
 395                 * a '+' entry produces this for file-1.
 396                 */
 397                temp->name = "/dev/null";
 398                strcpy(temp->hex, ".");
 399                strcpy(temp->mode, ".");
 400                return;
 401        }
 402
 403        if (!one->sha1_valid ||
 404            work_tree_matches(name, one->sha1)) {
 405                struct stat st;
 406                if (lstat(name, &st) < 0) {
 407                        if (errno == ENOENT)
 408                                goto not_a_valid_file;
 409                        die("stat(%s): %s", name, strerror(errno));
 410                }
 411                if (S_ISLNK(st.st_mode)) {
 412                        int ret;
 413                        char *buf, buf_[1024];
 414                        buf = ((sizeof(buf_) < st.st_size) ?
 415                               xmalloc(st.st_size) : buf_);
 416                        ret = readlink(name, buf, st.st_size);
 417                        if (ret < 0)
 418                                die("readlink(%s)", name);
 419                        prep_temp_blob(temp, buf, st.st_size,
 420                                       (one->sha1_valid ?
 421                                        one->sha1 : null_sha1),
 422                                       (one->sha1_valid ?
 423                                        one->mode : S_IFLNK));
 424                }
 425                else {
 426                        /* we can borrow from the file in the work tree */
 427                        temp->name = name;
 428                        if (!one->sha1_valid)
 429                                strcpy(temp->hex, sha1_to_hex(null_sha1));
 430                        else
 431                                strcpy(temp->hex, sha1_to_hex(one->sha1));
 432                        /* Even though we may sometimes borrow the
 433                         * contents from the work tree, we always want
 434                         * one->mode.  mode is trustworthy even when
 435                         * !(one->sha1_valid), as long as
 436                         * DIFF_FILE_VALID(one).
 437                         */
 438                        sprintf(temp->mode, "%06o", one->mode);
 439                }
 440                return;
 441        }
 442        else {
 443                if (diff_populate_filespec(one, 0))
 444                        die("cannot read data blob for %s", one->path);
 445                prep_temp_blob(temp, one->data, one->size,
 446                               one->sha1, one->mode);
 447        }
 448}
 449
 450static void remove_tempfile(void)
 451{
 452        int i;
 453
 454        for (i = 0; i < 2; i++)
 455                if (diff_temp[i].name == diff_temp[i].tmp_path) {
 456                        unlink(diff_temp[i].name);
 457                        diff_temp[i].name = NULL;
 458                }
 459}
 460
 461static void remove_tempfile_on_signal(int signo)
 462{
 463        remove_tempfile();
 464}
 465
 466/* An external diff command takes:
 467 *
 468 * diff-cmd name infile1 infile1-sha1 infile1-mode \
 469 *               infile2 infile2-sha1 infile2-mode [ rename-to ]
 470 *
 471 */
 472static void run_external_diff(const char *pgm,
 473                              const char *name,
 474                              const char *other,
 475                              struct diff_filespec *one,
 476                              struct diff_filespec *two,
 477                              const char *xfrm_msg)
 478{
 479        struct diff_tempfile *temp = diff_temp;
 480        pid_t pid;
 481        int status;
 482        static int atexit_asked = 0;
 483
 484        if (one && two) {
 485                prepare_temp_file(name, &temp[0], one);
 486                prepare_temp_file(other ? : name, &temp[1], two);
 487                if (! atexit_asked &&
 488                    (temp[0].name == temp[0].tmp_path ||
 489                     temp[1].name == temp[1].tmp_path)) {
 490                        atexit_asked = 1;
 491                        atexit(remove_tempfile);
 492                }
 493                signal(SIGINT, remove_tempfile_on_signal);
 494        }
 495
 496        fflush(NULL);
 497        pid = fork();
 498        if (pid < 0)
 499                die("unable to fork");
 500        if (!pid) {
 501                if (pgm) {
 502                        if (one && two) {
 503                                const char *exec_arg[10];
 504                                const char **arg = &exec_arg[0];
 505                                *arg++ = pgm;
 506                                *arg++ = name;
 507                                *arg++ = temp[0].name;
 508                                *arg++ = temp[0].hex;
 509                                *arg++ = temp[0].mode;
 510                                *arg++ = temp[1].name;
 511                                *arg++ = temp[1].hex;
 512                                *arg++ = temp[1].mode;
 513                                if (other) {
 514                                        *arg++ = other;
 515                                        *arg++ = xfrm_msg;
 516                                }
 517                                *arg = NULL;
 518                                execvp(pgm, (char *const*) exec_arg);
 519                        }
 520                        else
 521                                execlp(pgm, pgm, name, NULL);
 522                }
 523                /*
 524                 * otherwise we use the built-in one.
 525                 */
 526                if (one && two)
 527                        builtin_diff(name, other ? : name, temp, xfrm_msg);
 528                else
 529                        printf("* Unmerged path %s\n", name);
 530                exit(0);
 531        }
 532        if (waitpid(pid, &status, 0) < 0 ||
 533            !WIFEXITED(status) || WEXITSTATUS(status)) {
 534                /* Earlier we did not check the exit status because
 535                 * diff exits non-zero if files are different, and
 536                 * we are not interested in knowing that.  It was a
 537                 * mistake which made it harder to quit a diff-*
 538                 * session that uses the git-apply-patch-script as
 539                 * the GIT_EXTERNAL_DIFF.  A custom GIT_EXTERNAL_DIFF
 540                 * should also exit non-zero only when it wants to
 541                 * abort the entire diff-* session.
 542                 */
 543                remove_tempfile();
 544                fprintf(stderr, "external diff died, stopping at %s.\n", name);
 545                exit(1);
 546        }
 547        remove_tempfile();
 548}
 549
 550static void run_diff(const char *name,
 551                     const char *other,
 552                     struct diff_filespec *one,
 553                     struct diff_filespec *two,
 554                     const char *xfrm_msg)
 555{
 556        const char *pgm = external_diff();
 557        if (!pgm &&
 558            DIFF_FILE_VALID(one) && DIFF_FILE_VALID(two) &&
 559            (S_IFMT & one->mode) != (S_IFMT & two->mode)) {
 560                /* a filepair that changes between file and symlink
 561                 * needs to be split into deletion and creation.
 562                 */
 563                struct diff_filespec *null = alloc_filespec(two->path);
 564                run_external_diff(NULL, name, other, one, null, xfrm_msg);
 565                free(null);
 566                null = alloc_filespec(one->path);
 567                run_external_diff(NULL, name, other, null, two, xfrm_msg);
 568                free(null);
 569        }
 570        else
 571                run_external_diff(pgm, name, other, one, two, xfrm_msg);
 572}
 573
 574void diff_setup(int flags)
 575{
 576        if (flags & DIFF_SETUP_REVERSE)
 577                reverse_diff = 1;
 578        if (flags & DIFF_SETUP_USE_CACHE) {
 579                if (!active_cache)
 580                        /* read-cache does not die even when it fails
 581                         * so it is safe for us to do this here.  Also
 582                         * it does not smudge active_cache or active_nr
 583                         * when it fails, so we do not have to worry about
 584                         * cleaning it up oufselves either.
 585                         */
 586                        read_cache();
 587        }
 588        if (flags & DIFF_SETUP_USE_SIZE_CACHE)
 589                use_size_cache = 1;
 590        
 591}
 592
 593static int parse_num(const char **cp_p)
 594{
 595        int num, scale, ch, cnt;
 596        const char *cp = *cp_p;
 597
 598        cnt = num = 0;
 599        scale = 1;
 600        while ('0' <= (ch = *cp) && ch <= '9') {
 601                if (cnt++ < 5) {
 602                        /* We simply ignore more than 5 digits precision. */
 603                        scale *= 10;
 604                        num = num * 10 + ch - '0';
 605                }
 606                *cp++;
 607        }
 608        *cp_p = cp;
 609
 610        /* user says num divided by scale and we say internally that
 611         * is MAX_SCORE * num / scale.
 612         */
 613        return (MAX_SCORE * num / scale);
 614}
 615
 616int diff_scoreopt_parse(const char *opt)
 617{
 618        int opt1, opt2, cmd;
 619
 620        if (*opt++ != '-')
 621                return -1;
 622        cmd = *opt++;
 623        if (cmd != 'M' && cmd != 'C' && cmd != 'B')
 624                return -1; /* that is not a -M, -C nor -B option */
 625
 626        opt1 = parse_num(&opt);
 627        if (cmd != 'B')
 628                opt2 = 0;
 629        else {
 630                if (*opt == 0)
 631                        opt2 = 0;
 632                else if (*opt != '/')
 633                        return -1; /* we expect -B80/99 or -B80 */
 634                else {
 635                        opt++;
 636                        opt2 = parse_num(&opt);
 637                }
 638        }
 639        if (*opt != 0)
 640                return -1;
 641        return opt1 | (opt2 << 16);
 642}
 643
 644struct diff_queue_struct diff_queued_diff;
 645
 646void diff_q(struct diff_queue_struct *queue, struct diff_filepair *dp)
 647{
 648        if (queue->alloc <= queue->nr) {
 649                queue->alloc = alloc_nr(queue->alloc);
 650                queue->queue = xrealloc(queue->queue,
 651                                        sizeof(dp) * queue->alloc);
 652        }
 653        queue->queue[queue->nr++] = dp;
 654}
 655
 656struct diff_filepair *diff_queue(struct diff_queue_struct *queue,
 657                                 struct diff_filespec *one,
 658                                 struct diff_filespec *two)
 659{
 660        struct diff_filepair *dp = xmalloc(sizeof(*dp));
 661        dp->one = one;
 662        dp->two = two;
 663        dp->score = 0;
 664        dp->source_stays = 0;
 665        dp->broken_pair = 0;
 666        diff_q(queue, dp);
 667        return dp;
 668}
 669
 670void diff_free_filepair(struct diff_filepair *p)
 671{
 672        diff_free_filespec_data(p->one);
 673        diff_free_filespec_data(p->two);
 674        free(p);
 675}
 676
 677static void diff_flush_raw(struct diff_filepair *p,
 678                           int line_termination,
 679                           int inter_name_termination)
 680{
 681        int two_paths;
 682        char status[10];
 683
 684        if (line_termination) {
 685                const char *err = "path %s cannot be expressed without -z";
 686                if (strchr(p->one->path, line_termination) ||
 687                    strchr(p->one->path, inter_name_termination))
 688                        die(err, p->one->path);
 689                if (strchr(p->two->path, line_termination) ||
 690                    strchr(p->two->path, inter_name_termination))
 691                        die(err, p->two->path);
 692        }
 693
 694        switch (p->status) {
 695        case 'C': case 'R':
 696                two_paths = 1;
 697                sprintf(status, "%c%03d", p->status,
 698                        (int)(0.5 + p->score * 100.0/MAX_SCORE));
 699                break;
 700        case 'N': case 'D':
 701                two_paths = 0;
 702                if (p->score)
 703                        sprintf(status, "%c%03d", p->status,
 704                                (int)(0.5 + p->score * 100.0/MAX_SCORE));
 705                else {
 706                        status[0] = p->status;
 707                        status[1] = 0;
 708                }
 709                break;
 710        default:
 711                two_paths = 0;
 712                status[0] = p->status;
 713                status[1] = 0;
 714                break;
 715        }
 716        printf(":%06o %06o %s ",
 717               p->one->mode, p->two->mode, sha1_to_hex(p->one->sha1));
 718        printf("%s %s%c%s",
 719               sha1_to_hex(p->two->sha1),
 720               status,
 721               inter_name_termination,
 722               p->one->path);
 723        if (two_paths)
 724                printf("%c%s", inter_name_termination, p->two->path);
 725        putchar(line_termination);
 726}
 727
 728int diff_unmodified_pair(struct diff_filepair *p)
 729{
 730        /* This function is written stricter than necessary to support
 731         * the currently implemented transformers, but the idea is to
 732         * let transformers to produce diff_filepairs any way they want,
 733         * and filter and clean them up here before producing the output.
 734         */
 735        struct diff_filespec *one, *two;
 736
 737        if (DIFF_PAIR_UNMERGED(p))
 738                return 0; /* unmerged is interesting */
 739
 740        one = p->one;
 741        two = p->two;
 742
 743        /* deletion, addition, mode or type change
 744         * and rename are all interesting.
 745         */
 746        if (DIFF_FILE_VALID(one) != DIFF_FILE_VALID(two) ||
 747            DIFF_PAIR_MODE_CHANGED(p) ||
 748            strcmp(one->path, two->path))
 749                return 0;
 750
 751        /* both are valid and point at the same path.  that is, we are
 752         * dealing with a change.
 753         */
 754        if (one->sha1_valid && two->sha1_valid &&
 755            !memcmp(one->sha1, two->sha1, sizeof(one->sha1)))
 756                return 1; /* no change */
 757        if (!one->sha1_valid && !two->sha1_valid)
 758                return 1; /* both look at the same file on the filesystem. */
 759        return 0;
 760}
 761
 762static void diff_flush_patch(struct diff_filepair *p)
 763{
 764        const char *name, *other;
 765        char msg_[PATH_MAX*2+200], *msg;
 766
 767        if (diff_unmodified_pair(p))
 768                return;
 769
 770        name = p->one->path;
 771        other = (strcmp(name, p->two->path) ? p->two->path : NULL);
 772        if ((DIFF_FILE_VALID(p->one) && S_ISDIR(p->one->mode)) ||
 773            (DIFF_FILE_VALID(p->two) && S_ISDIR(p->two->mode)))
 774                return; /* no tree diffs in patch format */ 
 775
 776        switch (p->status) {
 777        case 'C':
 778                sprintf(msg_,
 779                        "similarity index %d%%\n"
 780                        "copy from %s\n"
 781                        "copy to %s",
 782                        (int)(0.5 + p->score * 100.0/MAX_SCORE),
 783                        p->one->path, p->two->path);
 784                msg = msg_;
 785                break;
 786        case 'R':
 787                sprintf(msg_,
 788                        "similarity index %d%%\n"
 789                        "rename from %s\n"
 790                        "rename to %s",
 791                        (int)(0.5 + p->score * 100.0/MAX_SCORE),
 792                        p->one->path, p->two->path);
 793                msg = msg_;
 794                break;
 795        case 'D': case 'N':
 796                if (DIFF_PAIR_BROKEN(p)) {
 797                        sprintf(msg_,
 798                                "dissimilarity index %d%%",
 799                                (int)(0.5 + p->score * 100.0/MAX_SCORE));
 800                        msg = msg_;
 801                }
 802                else
 803                        msg = NULL;
 804                break;
 805        default:
 806                msg = NULL;
 807        }
 808
 809        if (DIFF_PAIR_UNMERGED(p))
 810                run_diff(name, NULL, NULL, NULL, NULL);
 811        else
 812                run_diff(name, other, p->one, p->two, msg);
 813}
 814
 815int diff_queue_is_empty(void)
 816{
 817        struct diff_queue_struct *q = &diff_queued_diff;
 818        int i;
 819        for (i = 0; i < q->nr; i++)
 820                if (!diff_unmodified_pair(q->queue[i]))
 821                        return 0;
 822        return 1;
 823}
 824
 825#if DIFF_DEBUG
 826void diff_debug_filespec(struct diff_filespec *s, int x, const char *one)
 827{
 828        fprintf(stderr, "queue[%d] %s (%s) %s %06o %s\n",
 829                x, one ? : "",
 830                s->path,
 831                DIFF_FILE_VALID(s) ? "valid" : "invalid",
 832                s->mode,
 833                s->sha1_valid ? sha1_to_hex(s->sha1) : "");
 834        fprintf(stderr, "queue[%d] %s size %lu flags %d\n",
 835                x, one ? : "",
 836                s->size, s->xfrm_flags);
 837}
 838
 839void diff_debug_filepair(const struct diff_filepair *p, int i)
 840{
 841        diff_debug_filespec(p->one, i, "one");
 842        diff_debug_filespec(p->two, i, "two");
 843        fprintf(stderr, "score %d, status %c stays %d broken %d\n",
 844                p->score, p->status ? : '?',
 845                p->source_stays, p->broken_pair);
 846}
 847
 848void diff_debug_queue(const char *msg, struct diff_queue_struct *q)
 849{
 850        int i;
 851        if (msg)
 852                fprintf(stderr, "%s\n", msg);
 853        fprintf(stderr, "q->nr = %d\n", q->nr);
 854        for (i = 0; i < q->nr; i++) {
 855                struct diff_filepair *p = q->queue[i];
 856                diff_debug_filepair(p, i);
 857        }
 858}
 859#endif
 860
 861static void diff_resolve_rename_copy(void)
 862{
 863        int i, j;
 864        struct diff_filepair *p, *pp;
 865        struct diff_queue_struct *q = &diff_queued_diff;
 866
 867        diff_debug_queue("resolve-rename-copy", q);
 868
 869        for (i = 0; i < q->nr; i++) {
 870                p = q->queue[i];
 871                p->status = 0; /* undecided */
 872                if (DIFF_PAIR_UNMERGED(p))
 873                        p->status = 'U';
 874                else if (!DIFF_FILE_VALID(p->one))
 875                        p->status = 'N';
 876                else if (!DIFF_FILE_VALID(p->two))
 877                        p->status = 'D';
 878                else if (DIFF_PAIR_TYPE_CHANGED(p))
 879                        p->status = 'T';
 880
 881                /* from this point on, we are dealing with a pair
 882                 * whose both sides are valid and of the same type, i.e.
 883                 * either in-place edit or rename/copy edit.
 884                 */
 885                else if (DIFF_PAIR_RENAME(p)) {
 886                        if (p->source_stays) {
 887                                p->status = 'C';
 888                                continue;
 889                        }
 890                        /* See if there is some other filepair that
 891                         * copies from the same source as us.  If so
 892                         * we are a copy.  Otherwise we are a rename.
 893                         */
 894                        for (j = i + 1; j < q->nr; j++) {
 895                                pp = q->queue[j];
 896                                if (strcmp(pp->one->path, p->one->path))
 897                                        continue; /* not us */
 898                                if (!DIFF_PAIR_RENAME(pp))
 899                                        continue; /* not a rename/copy */
 900                                /* pp is a rename/copy from the same source */
 901                                p->status = 'C';
 902                                break;
 903                        }
 904                        if (!p->status)
 905                                p->status = 'R';
 906                }
 907                else if (memcmp(p->one->sha1, p->two->sha1, 20) ||
 908                         p->one->mode != p->two->mode)
 909                        p->status = 'M';
 910                else {
 911                        /* This is a "no-change" entry and should not
 912                         * happen anymore, but prepare for broken callers.
 913                         */
 914                        error("feeding unmodified %s to diffcore",
 915                              p->one->path);
 916                        p->status = 'X';
 917                }
 918        }
 919        diff_debug_queue("resolve-rename-copy done", q);
 920}
 921
 922void diff_flush(int diff_output_style, int resolve_rename_copy)
 923{
 924        struct diff_queue_struct *q = &diff_queued_diff;
 925        int i;
 926        int line_termination = '\n';
 927        int inter_name_termination = '\t';
 928
 929        if (diff_output_style == DIFF_FORMAT_MACHINE)
 930                line_termination = inter_name_termination = 0;
 931        if (resolve_rename_copy)
 932                diff_resolve_rename_copy();
 933
 934        for (i = 0; i < q->nr; i++) {
 935                struct diff_filepair *p = q->queue[i];
 936                if ((diff_output_style == DIFF_FORMAT_NO_OUTPUT) ||
 937                    (p->status == 'X'))
 938                        continue;
 939                if (p->status == 0)
 940                        die("internal error in diff-resolve-rename-copy");
 941                switch (diff_output_style) {
 942                case DIFF_FORMAT_PATCH:
 943                        diff_flush_patch(p);
 944                        break;
 945                case DIFF_FORMAT_HUMAN:
 946                case DIFF_FORMAT_MACHINE:
 947                        diff_flush_raw(p, line_termination,
 948                                       inter_name_termination);
 949                        break;
 950                }
 951        }
 952        for (i = 0; i < q->nr; i++)
 953                diff_free_filepair(q->queue[i]);
 954        free(q->queue);
 955        q->queue = NULL;
 956        q->nr = q->alloc = 0;
 957}
 958
 959void diffcore_std(const char **paths,
 960                  int detect_rename, int rename_score,
 961                  const char *pickaxe, int pickaxe_opts,
 962                  int break_opt,
 963                  const char *orderfile)
 964{
 965        if (paths && paths[0])
 966                diffcore_pathspec(paths);
 967        if (break_opt != -1)
 968                diffcore_break(break_opt);
 969        if (detect_rename)
 970                diffcore_rename(detect_rename, rename_score);
 971        if (break_opt != -1)
 972                diffcore_merge_broken();
 973        if (pickaxe)
 974                diffcore_pickaxe(pickaxe, pickaxe_opts);
 975        if (orderfile)
 976                diffcore_order(orderfile);
 977}
 978
 979void diff_addremove(int addremove, unsigned mode,
 980                    const unsigned char *sha1,
 981                    const char *base, const char *path)
 982{
 983        char concatpath[PATH_MAX];
 984        struct diff_filespec *one, *two;
 985
 986        /* This may look odd, but it is a preparation for
 987         * feeding "there are unchanged files which should
 988         * not produce diffs, but when you are doing copy
 989         * detection you would need them, so here they are"
 990         * entries to the diff-core.  They will be prefixed
 991         * with something like '=' or '*' (I haven't decided
 992         * which but should not make any difference).
 993         * Feeding the same new and old to diff_change() 
 994         * also has the same effect.
 995         * Before the final output happens, they are pruned after
 996         * merged into rename/copy pairs as appropriate.
 997         */
 998        if (reverse_diff)
 999                addremove = (addremove == '+' ? '-' :
1000                             addremove == '-' ? '+' : addremove);
1001
1002        if (!path) path = "";
1003        sprintf(concatpath, "%s%s", base, path);
1004        one = alloc_filespec(concatpath);
1005        two = alloc_filespec(concatpath);
1006
1007        if (addremove != '+')
1008                fill_filespec(one, sha1, mode);
1009        if (addremove != '-')
1010                fill_filespec(two, sha1, mode);
1011
1012        diff_queue(&diff_queued_diff, one, two);
1013}
1014
1015void diff_helper_input(unsigned old_mode,
1016                       unsigned new_mode,
1017                       const unsigned char *old_sha1,
1018                       const unsigned char *new_sha1,
1019                       const char *old_path,
1020                       int status,
1021                       int score,
1022                       const char *new_path)
1023{
1024        struct diff_filespec *one, *two;
1025        struct diff_filepair *dp;
1026
1027        one = alloc_filespec(old_path);
1028        two = alloc_filespec(new_path);
1029        if (old_mode)
1030                fill_filespec(one, old_sha1, old_mode);
1031        if (new_mode)
1032                fill_filespec(two, new_sha1, new_mode);
1033        dp = diff_queue(&diff_queued_diff, one, two);
1034        dp->score = score * MAX_SCORE / 100;
1035        dp->status = status;
1036}
1037
1038void diff_change(unsigned old_mode, unsigned new_mode,
1039                 const unsigned char *old_sha1,
1040                 const unsigned char *new_sha1,
1041                 const char *base, const char *path) 
1042{
1043        char concatpath[PATH_MAX];
1044        struct diff_filespec *one, *two;
1045
1046        if (reverse_diff) {
1047                unsigned tmp;
1048                const unsigned char *tmp_c;
1049                tmp = old_mode; old_mode = new_mode; new_mode = tmp;
1050                tmp_c = old_sha1; old_sha1 = new_sha1; new_sha1 = tmp_c;
1051        }
1052        if (!path) path = "";
1053        sprintf(concatpath, "%s%s", base, path);
1054        one = alloc_filespec(concatpath);
1055        two = alloc_filespec(concatpath);
1056        fill_filespec(one, old_sha1, old_mode);
1057        fill_filespec(two, new_sha1, new_mode);
1058
1059        diff_queue(&diff_queued_diff, one, two);
1060}
1061
1062void diff_unmerge(const char *path)
1063{
1064        struct diff_filespec *one, *two;
1065        one = alloc_filespec(path);
1066        two = alloc_filespec(path);
1067        diff_queue(&diff_queued_diff, one, two);
1068}