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