builtin / apply.con commit Merge branch 'sc/http-late-auth' (f350e1f)
   1/*
   2 * apply.c
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 *
   6 * This applies patches on top of some (arbitrary) version of the SCM.
   7 *
   8 */
   9#include "cache.h"
  10#include "cache-tree.h"
  11#include "quote.h"
  12#include "blob.h"
  13#include "delta.h"
  14#include "builtin.h"
  15#include "string-list.h"
  16#include "dir.h"
  17#include "parse-options.h"
  18
  19/*
  20 *  --check turns on checking that the working tree matches the
  21 *    files that are being modified, but doesn't apply the patch
  22 *  --stat does just a diffstat, and doesn't actually apply
  23 *  --numstat does numeric diffstat, and doesn't actually apply
  24 *  --index-info shows the old and new index info for paths if available.
  25 *  --index updates the cache as well.
  26 *  --cached updates only the cache without ever touching the working tree.
  27 */
  28static const char *prefix;
  29static int prefix_length = -1;
  30static int newfd = -1;
  31
  32static int unidiff_zero;
  33static int p_value = 1;
  34static int p_value_known;
  35static int check_index;
  36static int update_index;
  37static int cached;
  38static int diffstat;
  39static int numstat;
  40static int summary;
  41static int check;
  42static int apply = 1;
  43static int apply_in_reverse;
  44static int apply_with_reject;
  45static int apply_verbosely;
  46static int no_add;
  47static const char *fake_ancestor;
  48static int line_termination = '\n';
  49static unsigned int p_context = UINT_MAX;
  50static const char * const apply_usage[] = {
  51        "git apply [options] [<patch>...]",
  52        NULL
  53};
  54
  55static enum ws_error_action {
  56        nowarn_ws_error,
  57        warn_on_ws_error,
  58        die_on_ws_error,
  59        correct_ws_error,
  60} ws_error_action = warn_on_ws_error;
  61static int whitespace_error;
  62static int squelch_whitespace_errors = 5;
  63static int applied_after_fixing_ws;
  64
  65static enum ws_ignore {
  66        ignore_ws_none,
  67        ignore_ws_change,
  68} ws_ignore_action = ignore_ws_none;
  69
  70
  71static const char *patch_input_file;
  72static const char *root;
  73static int root_len;
  74static int read_stdin = 1;
  75static int options;
  76
  77static void parse_whitespace_option(const char *option)
  78{
  79        if (!option) {
  80                ws_error_action = warn_on_ws_error;
  81                return;
  82        }
  83        if (!strcmp(option, "warn")) {
  84                ws_error_action = warn_on_ws_error;
  85                return;
  86        }
  87        if (!strcmp(option, "nowarn")) {
  88                ws_error_action = nowarn_ws_error;
  89                return;
  90        }
  91        if (!strcmp(option, "error")) {
  92                ws_error_action = die_on_ws_error;
  93                return;
  94        }
  95        if (!strcmp(option, "error-all")) {
  96                ws_error_action = die_on_ws_error;
  97                squelch_whitespace_errors = 0;
  98                return;
  99        }
 100        if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
 101                ws_error_action = correct_ws_error;
 102                return;
 103        }
 104        die("unrecognized whitespace option '%s'", option);
 105}
 106
 107static void parse_ignorewhitespace_option(const char *option)
 108{
 109        if (!option || !strcmp(option, "no") ||
 110            !strcmp(option, "false") || !strcmp(option, "never") ||
 111            !strcmp(option, "none")) {
 112                ws_ignore_action = ignore_ws_none;
 113                return;
 114        }
 115        if (!strcmp(option, "change")) {
 116                ws_ignore_action = ignore_ws_change;
 117                return;
 118        }
 119        die("unrecognized whitespace ignore option '%s'", option);
 120}
 121
 122static void set_default_whitespace_mode(const char *whitespace_option)
 123{
 124        if (!whitespace_option && !apply_default_whitespace)
 125                ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
 126}
 127
 128/*
 129 * For "diff-stat" like behaviour, we keep track of the biggest change
 130 * we've seen, and the longest filename. That allows us to do simple
 131 * scaling.
 132 */
 133static int max_change, max_len;
 134
 135/*
 136 * Various "current state", notably line numbers and what
 137 * file (and how) we're patching right now.. The "is_xxxx"
 138 * things are flags, where -1 means "don't know yet".
 139 */
 140static int linenr = 1;
 141
 142/*
 143 * This represents one "hunk" from a patch, starting with
 144 * "@@ -oldpos,oldlines +newpos,newlines @@" marker.  The
 145 * patch text is pointed at by patch, and its byte length
 146 * is stored in size.  leading and trailing are the number
 147 * of context lines.
 148 */
 149struct fragment {
 150        unsigned long leading, trailing;
 151        unsigned long oldpos, oldlines;
 152        unsigned long newpos, newlines;
 153        const char *patch;
 154        int size;
 155        int rejected;
 156        int linenr;
 157        struct fragment *next;
 158};
 159
 160/*
 161 * When dealing with a binary patch, we reuse "leading" field
 162 * to store the type of the binary hunk, either deflated "delta"
 163 * or deflated "literal".
 164 */
 165#define binary_patch_method leading
 166#define BINARY_DELTA_DEFLATED   1
 167#define BINARY_LITERAL_DEFLATED 2
 168
 169/*
 170 * This represents a "patch" to a file, both metainfo changes
 171 * such as creation/deletion, filemode and content changes represented
 172 * as a series of fragments.
 173 */
 174struct patch {
 175        char *new_name, *old_name, *def_name;
 176        unsigned int old_mode, new_mode;
 177        int is_new, is_delete;  /* -1 = unknown, 0 = false, 1 = true */
 178        int rejected;
 179        unsigned ws_rule;
 180        unsigned long deflate_origlen;
 181        int lines_added, lines_deleted;
 182        int score;
 183        unsigned int is_toplevel_relative:1;
 184        unsigned int inaccurate_eof:1;
 185        unsigned int is_binary:1;
 186        unsigned int is_copy:1;
 187        unsigned int is_rename:1;
 188        unsigned int recount:1;
 189        struct fragment *fragments;
 190        char *result;
 191        size_t resultsize;
 192        char old_sha1_prefix[41];
 193        char new_sha1_prefix[41];
 194        struct patch *next;
 195};
 196
 197/*
 198 * A line in a file, len-bytes long (includes the terminating LF,
 199 * except for an incomplete line at the end if the file ends with
 200 * one), and its contents hashes to 'hash'.
 201 */
 202struct line {
 203        size_t len;
 204        unsigned hash : 24;
 205        unsigned flag : 8;
 206#define LINE_COMMON     1
 207};
 208
 209/*
 210 * This represents a "file", which is an array of "lines".
 211 */
 212struct image {
 213        char *buf;
 214        size_t len;
 215        size_t nr;
 216        size_t alloc;
 217        struct line *line_allocated;
 218        struct line *line;
 219};
 220
 221/*
 222 * Records filenames that have been touched, in order to handle
 223 * the case where more than one patches touch the same file.
 224 */
 225
 226static struct string_list fn_table;
 227
 228static uint32_t hash_line(const char *cp, size_t len)
 229{
 230        size_t i;
 231        uint32_t h;
 232        for (i = 0, h = 0; i < len; i++) {
 233                if (!isspace(cp[i])) {
 234                        h = h * 3 + (cp[i] & 0xff);
 235                }
 236        }
 237        return h;
 238}
 239
 240/*
 241 * Compare lines s1 of length n1 and s2 of length n2, ignoring
 242 * whitespace difference. Returns 1 if they match, 0 otherwise
 243 */
 244static int fuzzy_matchlines(const char *s1, size_t n1,
 245                            const char *s2, size_t n2)
 246{
 247        const char *last1 = s1 + n1 - 1;
 248        const char *last2 = s2 + n2 - 1;
 249        int result = 0;
 250
 251        if (n1 < 0 || n2 < 0)
 252                return 0;
 253
 254        /* ignore line endings */
 255        while ((*last1 == '\r') || (*last1 == '\n'))
 256                last1--;
 257        while ((*last2 == '\r') || (*last2 == '\n'))
 258                last2--;
 259
 260        /* skip leading whitespace */
 261        while (isspace(*s1) && (s1 <= last1))
 262                s1++;
 263        while (isspace(*s2) && (s2 <= last2))
 264                s2++;
 265        /* early return if both lines are empty */
 266        if ((s1 > last1) && (s2 > last2))
 267                return 1;
 268        while (!result) {
 269                result = *s1++ - *s2++;
 270                /*
 271                 * Skip whitespace inside. We check for whitespace on
 272                 * both buffers because we don't want "a b" to match
 273                 * "ab"
 274                 */
 275                if (isspace(*s1) && isspace(*s2)) {
 276                        while (isspace(*s1) && s1 <= last1)
 277                                s1++;
 278                        while (isspace(*s2) && s2 <= last2)
 279                                s2++;
 280                }
 281                /*
 282                 * If we reached the end on one side only,
 283                 * lines don't match
 284                 */
 285                if (
 286                    ((s2 > last2) && (s1 <= last1)) ||
 287                    ((s1 > last1) && (s2 <= last2)))
 288                        return 0;
 289                if ((s1 > last1) && (s2 > last2))
 290                        break;
 291        }
 292
 293        return !result;
 294}
 295
 296static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
 297{
 298        ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
 299        img->line_allocated[img->nr].len = len;
 300        img->line_allocated[img->nr].hash = hash_line(bol, len);
 301        img->line_allocated[img->nr].flag = flag;
 302        img->nr++;
 303}
 304
 305static void prepare_image(struct image *image, char *buf, size_t len,
 306                          int prepare_linetable)
 307{
 308        const char *cp, *ep;
 309
 310        memset(image, 0, sizeof(*image));
 311        image->buf = buf;
 312        image->len = len;
 313
 314        if (!prepare_linetable)
 315                return;
 316
 317        ep = image->buf + image->len;
 318        cp = image->buf;
 319        while (cp < ep) {
 320                const char *next;
 321                for (next = cp; next < ep && *next != '\n'; next++)
 322                        ;
 323                if (next < ep)
 324                        next++;
 325                add_line_info(image, cp, next - cp, 0);
 326                cp = next;
 327        }
 328        image->line = image->line_allocated;
 329}
 330
 331static void clear_image(struct image *image)
 332{
 333        free(image->buf);
 334        image->buf = NULL;
 335        image->len = 0;
 336}
 337
 338static void say_patch_name(FILE *output, const char *pre,
 339                           struct patch *patch, const char *post)
 340{
 341        fputs(pre, output);
 342        if (patch->old_name && patch->new_name &&
 343            strcmp(patch->old_name, patch->new_name)) {
 344                quote_c_style(patch->old_name, NULL, output, 0);
 345                fputs(" => ", output);
 346                quote_c_style(patch->new_name, NULL, output, 0);
 347        } else {
 348                const char *n = patch->new_name;
 349                if (!n)
 350                        n = patch->old_name;
 351                quote_c_style(n, NULL, output, 0);
 352        }
 353        fputs(post, output);
 354}
 355
 356#define CHUNKSIZE (8192)
 357#define SLOP (16)
 358
 359static void read_patch_file(struct strbuf *sb, int fd)
 360{
 361        if (strbuf_read(sb, fd, 0) < 0)
 362                die_errno("git apply: failed to read");
 363
 364        /*
 365         * Make sure that we have some slop in the buffer
 366         * so that we can do speculative "memcmp" etc, and
 367         * see to it that it is NUL-filled.
 368         */
 369        strbuf_grow(sb, SLOP);
 370        memset(sb->buf + sb->len, 0, SLOP);
 371}
 372
 373static unsigned long linelen(const char *buffer, unsigned long size)
 374{
 375        unsigned long len = 0;
 376        while (size--) {
 377                len++;
 378                if (*buffer++ == '\n')
 379                        break;
 380        }
 381        return len;
 382}
 383
 384static int is_dev_null(const char *str)
 385{
 386        return !memcmp("/dev/null", str, 9) && isspace(str[9]);
 387}
 388
 389#define TERM_SPACE      1
 390#define TERM_TAB        2
 391
 392static int name_terminate(const char *name, int namelen, int c, int terminate)
 393{
 394        if (c == ' ' && !(terminate & TERM_SPACE))
 395                return 0;
 396        if (c == '\t' && !(terminate & TERM_TAB))
 397                return 0;
 398
 399        return 1;
 400}
 401
 402/* remove double slashes to make --index work with such filenames */
 403static char *squash_slash(char *name)
 404{
 405        int i = 0, j = 0;
 406
 407        if (!name)
 408                return NULL;
 409
 410        while (name[i]) {
 411                if ((name[j++] = name[i++]) == '/')
 412                        while (name[i] == '/')
 413                                i++;
 414        }
 415        name[j] = '\0';
 416        return name;
 417}
 418
 419static char *find_name(const char *line, char *def, int p_value, int terminate)
 420{
 421        int len;
 422        const char *start = NULL;
 423
 424        if (p_value == 0)
 425                start = line;
 426
 427        if (*line == '"') {
 428                struct strbuf name = STRBUF_INIT;
 429
 430                /*
 431                 * Proposed "new-style" GNU patch/diff format; see
 432                 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
 433                 */
 434                if (!unquote_c_style(&name, line, NULL)) {
 435                        char *cp;
 436
 437                        for (cp = name.buf; p_value; p_value--) {
 438                                cp = strchr(cp, '/');
 439                                if (!cp)
 440                                        break;
 441                                cp++;
 442                        }
 443                        if (cp) {
 444                                /* name can later be freed, so we need
 445                                 * to memmove, not just return cp
 446                                 */
 447                                strbuf_remove(&name, 0, cp - name.buf);
 448                                free(def);
 449                                if (root)
 450                                        strbuf_insert(&name, 0, root, root_len);
 451                                return squash_slash(strbuf_detach(&name, NULL));
 452                        }
 453                }
 454                strbuf_release(&name);
 455        }
 456
 457        for (;;) {
 458                char c = *line;
 459
 460                if (isspace(c)) {
 461                        if (c == '\n')
 462                                break;
 463                        if (name_terminate(start, line-start, c, terminate))
 464                                break;
 465                }
 466                line++;
 467                if (c == '/' && !--p_value)
 468                        start = line;
 469        }
 470        if (!start)
 471                return squash_slash(def);
 472        len = line - start;
 473        if (!len)
 474                return squash_slash(def);
 475
 476        /*
 477         * Generally we prefer the shorter name, especially
 478         * if the other one is just a variation of that with
 479         * something else tacked on to the end (ie "file.orig"
 480         * or "file~").
 481         */
 482        if (def) {
 483                int deflen = strlen(def);
 484                if (deflen < len && !strncmp(start, def, deflen))
 485                        return squash_slash(def);
 486                free(def);
 487        }
 488
 489        if (root) {
 490                char *ret = xmalloc(root_len + len + 1);
 491                strcpy(ret, root);
 492                memcpy(ret + root_len, start, len);
 493                ret[root_len + len] = '\0';
 494                return squash_slash(ret);
 495        }
 496
 497        return squash_slash(xmemdupz(start, len));
 498}
 499
 500static int count_slashes(const char *cp)
 501{
 502        int cnt = 0;
 503        char ch;
 504
 505        while ((ch = *cp++))
 506                if (ch == '/')
 507                        cnt++;
 508        return cnt;
 509}
 510
 511/*
 512 * Given the string after "--- " or "+++ ", guess the appropriate
 513 * p_value for the given patch.
 514 */
 515static int guess_p_value(const char *nameline)
 516{
 517        char *name, *cp;
 518        int val = -1;
 519
 520        if (is_dev_null(nameline))
 521                return -1;
 522        name = find_name(nameline, NULL, 0, TERM_SPACE | TERM_TAB);
 523        if (!name)
 524                return -1;
 525        cp = strchr(name, '/');
 526        if (!cp)
 527                val = 0;
 528        else if (prefix) {
 529                /*
 530                 * Does it begin with "a/$our-prefix" and such?  Then this is
 531                 * very likely to apply to our directory.
 532                 */
 533                if (!strncmp(name, prefix, prefix_length))
 534                        val = count_slashes(prefix);
 535                else {
 536                        cp++;
 537                        if (!strncmp(cp, prefix, prefix_length))
 538                                val = count_slashes(prefix) + 1;
 539                }
 540        }
 541        free(name);
 542        return val;
 543}
 544
 545/*
 546 * Does the ---/+++ line has the POSIX timestamp after the last HT?
 547 * GNU diff puts epoch there to signal a creation/deletion event.  Is
 548 * this such a timestamp?
 549 */
 550static int has_epoch_timestamp(const char *nameline)
 551{
 552        /*
 553         * We are only interested in epoch timestamp; any non-zero
 554         * fraction cannot be one, hence "(\.0+)?" in the regexp below.
 555         * For the same reason, the date must be either 1969-12-31 or
 556         * 1970-01-01, and the seconds part must be "00".
 557         */
 558        const char stamp_regexp[] =
 559                "^(1969-12-31|1970-01-01)"
 560                " "
 561                "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
 562                " "
 563                "([-+][0-2][0-9][0-5][0-9])\n";
 564        const char *timestamp = NULL, *cp;
 565        static regex_t *stamp;
 566        regmatch_t m[10];
 567        int zoneoffset;
 568        int hourminute;
 569        int status;
 570
 571        for (cp = nameline; *cp != '\n'; cp++) {
 572                if (*cp == '\t')
 573                        timestamp = cp + 1;
 574        }
 575        if (!timestamp)
 576                return 0;
 577        if (!stamp) {
 578                stamp = xmalloc(sizeof(*stamp));
 579                if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
 580                        warning("Cannot prepare timestamp regexp %s",
 581                                stamp_regexp);
 582                        return 0;
 583                }
 584        }
 585
 586        status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
 587        if (status) {
 588                if (status != REG_NOMATCH)
 589                        warning("regexec returned %d for input: %s",
 590                                status, timestamp);
 591                return 0;
 592        }
 593
 594        zoneoffset = strtol(timestamp + m[3].rm_so + 1, NULL, 10);
 595        zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
 596        if (timestamp[m[3].rm_so] == '-')
 597                zoneoffset = -zoneoffset;
 598
 599        /*
 600         * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
 601         * (west of GMT) or 1970-01-01 (east of GMT)
 602         */
 603        if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
 604            (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
 605                return 0;
 606
 607        hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
 608                      strtol(timestamp + 14, NULL, 10) -
 609                      zoneoffset);
 610
 611        return ((zoneoffset < 0 && hourminute == 1440) ||
 612                (0 <= zoneoffset && !hourminute));
 613}
 614
 615/*
 616 * Get the name etc info from the ---/+++ lines of a traditional patch header
 617 *
 618 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
 619 * files, we can happily check the index for a match, but for creating a
 620 * new file we should try to match whatever "patch" does. I have no idea.
 621 */
 622static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
 623{
 624        char *name;
 625
 626        first += 4;     /* skip "--- " */
 627        second += 4;    /* skip "+++ " */
 628        if (!p_value_known) {
 629                int p, q;
 630                p = guess_p_value(first);
 631                q = guess_p_value(second);
 632                if (p < 0) p = q;
 633                if (0 <= p && p == q) {
 634                        p_value = p;
 635                        p_value_known = 1;
 636                }
 637        }
 638        if (is_dev_null(first)) {
 639                patch->is_new = 1;
 640                patch->is_delete = 0;
 641                name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
 642                patch->new_name = name;
 643        } else if (is_dev_null(second)) {
 644                patch->is_new = 0;
 645                patch->is_delete = 1;
 646                name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
 647                patch->old_name = name;
 648        } else {
 649                name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
 650                name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
 651                if (has_epoch_timestamp(first)) {
 652                        patch->is_new = 1;
 653                        patch->is_delete = 0;
 654                        patch->new_name = name;
 655                } else if (has_epoch_timestamp(second)) {
 656                        patch->is_new = 0;
 657                        patch->is_delete = 1;
 658                        patch->old_name = name;
 659                } else {
 660                        patch->old_name = patch->new_name = name;
 661                }
 662        }
 663        if (!name)
 664                die("unable to find filename in patch at line %d", linenr);
 665}
 666
 667static int gitdiff_hdrend(const char *line, struct patch *patch)
 668{
 669        return -1;
 670}
 671
 672/*
 673 * We're anal about diff header consistency, to make
 674 * sure that we don't end up having strange ambiguous
 675 * patches floating around.
 676 *
 677 * As a result, gitdiff_{old|new}name() will check
 678 * their names against any previous information, just
 679 * to make sure..
 680 */
 681static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
 682{
 683        if (!orig_name && !isnull)
 684                return find_name(line, NULL, p_value, TERM_TAB);
 685
 686        if (orig_name) {
 687                int len;
 688                const char *name;
 689                char *another;
 690                name = orig_name;
 691                len = strlen(name);
 692                if (isnull)
 693                        die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
 694                another = find_name(line, NULL, p_value, TERM_TAB);
 695                if (!another || memcmp(another, name, len + 1))
 696                        die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
 697                free(another);
 698                return orig_name;
 699        }
 700        else {
 701                /* expect "/dev/null" */
 702                if (memcmp("/dev/null", line, 9) || line[9] != '\n')
 703                        die("git apply: bad git-diff - expected /dev/null on line %d", linenr);
 704                return NULL;
 705        }
 706}
 707
 708static int gitdiff_oldname(const char *line, struct patch *patch)
 709{
 710        patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
 711        return 0;
 712}
 713
 714static int gitdiff_newname(const char *line, struct patch *patch)
 715{
 716        patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
 717        return 0;
 718}
 719
 720static int gitdiff_oldmode(const char *line, struct patch *patch)
 721{
 722        patch->old_mode = strtoul(line, NULL, 8);
 723        return 0;
 724}
 725
 726static int gitdiff_newmode(const char *line, struct patch *patch)
 727{
 728        patch->new_mode = strtoul(line, NULL, 8);
 729        return 0;
 730}
 731
 732static int gitdiff_delete(const char *line, struct patch *patch)
 733{
 734        patch->is_delete = 1;
 735        patch->old_name = patch->def_name;
 736        return gitdiff_oldmode(line, patch);
 737}
 738
 739static int gitdiff_newfile(const char *line, struct patch *patch)
 740{
 741        patch->is_new = 1;
 742        patch->new_name = patch->def_name;
 743        return gitdiff_newmode(line, patch);
 744}
 745
 746static int gitdiff_copysrc(const char *line, struct patch *patch)
 747{
 748        patch->is_copy = 1;
 749        patch->old_name = find_name(line, NULL, 0, 0);
 750        return 0;
 751}
 752
 753static int gitdiff_copydst(const char *line, struct patch *patch)
 754{
 755        patch->is_copy = 1;
 756        patch->new_name = find_name(line, NULL, 0, 0);
 757        return 0;
 758}
 759
 760static int gitdiff_renamesrc(const char *line, struct patch *patch)
 761{
 762        patch->is_rename = 1;
 763        patch->old_name = find_name(line, NULL, 0, 0);
 764        return 0;
 765}
 766
 767static int gitdiff_renamedst(const char *line, struct patch *patch)
 768{
 769        patch->is_rename = 1;
 770        patch->new_name = find_name(line, NULL, 0, 0);
 771        return 0;
 772}
 773
 774static int gitdiff_similarity(const char *line, struct patch *patch)
 775{
 776        if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
 777                patch->score = 0;
 778        return 0;
 779}
 780
 781static int gitdiff_dissimilarity(const char *line, struct patch *patch)
 782{
 783        if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
 784                patch->score = 0;
 785        return 0;
 786}
 787
 788static int gitdiff_index(const char *line, struct patch *patch)
 789{
 790        /*
 791         * index line is N hexadecimal, "..", N hexadecimal,
 792         * and optional space with octal mode.
 793         */
 794        const char *ptr, *eol;
 795        int len;
 796
 797        ptr = strchr(line, '.');
 798        if (!ptr || ptr[1] != '.' || 40 < ptr - line)
 799                return 0;
 800        len = ptr - line;
 801        memcpy(patch->old_sha1_prefix, line, len);
 802        patch->old_sha1_prefix[len] = 0;
 803
 804        line = ptr + 2;
 805        ptr = strchr(line, ' ');
 806        eol = strchr(line, '\n');
 807
 808        if (!ptr || eol < ptr)
 809                ptr = eol;
 810        len = ptr - line;
 811
 812        if (40 < len)
 813                return 0;
 814        memcpy(patch->new_sha1_prefix, line, len);
 815        patch->new_sha1_prefix[len] = 0;
 816        if (*ptr == ' ')
 817                patch->old_mode = strtoul(ptr+1, NULL, 8);
 818        return 0;
 819}
 820
 821/*
 822 * This is normal for a diff that doesn't change anything: we'll fall through
 823 * into the next diff. Tell the parser to break out.
 824 */
 825static int gitdiff_unrecognized(const char *line, struct patch *patch)
 826{
 827        return -1;
 828}
 829
 830static const char *stop_at_slash(const char *line, int llen)
 831{
 832        int nslash = p_value;
 833        int i;
 834
 835        for (i = 0; i < llen; i++) {
 836                int ch = line[i];
 837                if (ch == '/' && --nslash <= 0)
 838                        return &line[i];
 839        }
 840        return NULL;
 841}
 842
 843/*
 844 * This is to extract the same name that appears on "diff --git"
 845 * line.  We do not find and return anything if it is a rename
 846 * patch, and it is OK because we will find the name elsewhere.
 847 * We need to reliably find name only when it is mode-change only,
 848 * creation or deletion of an empty file.  In any of these cases,
 849 * both sides are the same name under a/ and b/ respectively.
 850 */
 851static char *git_header_name(char *line, int llen)
 852{
 853        const char *name;
 854        const char *second = NULL;
 855        size_t len;
 856
 857        line += strlen("diff --git ");
 858        llen -= strlen("diff --git ");
 859
 860        if (*line == '"') {
 861                const char *cp;
 862                struct strbuf first = STRBUF_INIT;
 863                struct strbuf sp = STRBUF_INIT;
 864
 865                if (unquote_c_style(&first, line, &second))
 866                        goto free_and_fail1;
 867
 868                /* advance to the first slash */
 869                cp = stop_at_slash(first.buf, first.len);
 870                /* we do not accept absolute paths */
 871                if (!cp || cp == first.buf)
 872                        goto free_and_fail1;
 873                strbuf_remove(&first, 0, cp + 1 - first.buf);
 874
 875                /*
 876                 * second points at one past closing dq of name.
 877                 * find the second name.
 878                 */
 879                while ((second < line + llen) && isspace(*second))
 880                        second++;
 881
 882                if (line + llen <= second)
 883                        goto free_and_fail1;
 884                if (*second == '"') {
 885                        if (unquote_c_style(&sp, second, NULL))
 886                                goto free_and_fail1;
 887                        cp = stop_at_slash(sp.buf, sp.len);
 888                        if (!cp || cp == sp.buf)
 889                                goto free_and_fail1;
 890                        /* They must match, otherwise ignore */
 891                        if (strcmp(cp + 1, first.buf))
 892                                goto free_and_fail1;
 893                        strbuf_release(&sp);
 894                        return strbuf_detach(&first, NULL);
 895                }
 896
 897                /* unquoted second */
 898                cp = stop_at_slash(second, line + llen - second);
 899                if (!cp || cp == second)
 900                        goto free_and_fail1;
 901                cp++;
 902                if (line + llen - cp != first.len + 1 ||
 903                    memcmp(first.buf, cp, first.len))
 904                        goto free_and_fail1;
 905                return strbuf_detach(&first, NULL);
 906
 907        free_and_fail1:
 908                strbuf_release(&first);
 909                strbuf_release(&sp);
 910                return NULL;
 911        }
 912
 913        /* unquoted first name */
 914        name = stop_at_slash(line, llen);
 915        if (!name || name == line)
 916                return NULL;
 917        name++;
 918
 919        /*
 920         * since the first name is unquoted, a dq if exists must be
 921         * the beginning of the second name.
 922         */
 923        for (second = name; second < line + llen; second++) {
 924                if (*second == '"') {
 925                        struct strbuf sp = STRBUF_INIT;
 926                        const char *np;
 927
 928                        if (unquote_c_style(&sp, second, NULL))
 929                                goto free_and_fail2;
 930
 931                        np = stop_at_slash(sp.buf, sp.len);
 932                        if (!np || np == sp.buf)
 933                                goto free_and_fail2;
 934                        np++;
 935
 936                        len = sp.buf + sp.len - np;
 937                        if (len < second - name &&
 938                            !strncmp(np, name, len) &&
 939                            isspace(name[len])) {
 940                                /* Good */
 941                                strbuf_remove(&sp, 0, np - sp.buf);
 942                                return strbuf_detach(&sp, NULL);
 943                        }
 944
 945                free_and_fail2:
 946                        strbuf_release(&sp);
 947                        return NULL;
 948                }
 949        }
 950
 951        /*
 952         * Accept a name only if it shows up twice, exactly the same
 953         * form.
 954         */
 955        for (len = 0 ; ; len++) {
 956                switch (name[len]) {
 957                default:
 958                        continue;
 959                case '\n':
 960                        return NULL;
 961                case '\t': case ' ':
 962                        second = name+len;
 963                        for (;;) {
 964                                char c = *second++;
 965                                if (c == '\n')
 966                                        return NULL;
 967                                if (c == '/')
 968                                        break;
 969                        }
 970                        if (second[len] == '\n' && !memcmp(name, second, len)) {
 971                                return xmemdupz(name, len);
 972                        }
 973                }
 974        }
 975}
 976
 977/* Verify that we recognize the lines following a git header */
 978static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
 979{
 980        unsigned long offset;
 981
 982        /* A git diff has explicit new/delete information, so we don't guess */
 983        patch->is_new = 0;
 984        patch->is_delete = 0;
 985
 986        /*
 987         * Some things may not have the old name in the
 988         * rest of the headers anywhere (pure mode changes,
 989         * or removing or adding empty files), so we get
 990         * the default name from the header.
 991         */
 992        patch->def_name = git_header_name(line, len);
 993        if (patch->def_name && root) {
 994                char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
 995                strcpy(s, root);
 996                strcpy(s + root_len, patch->def_name);
 997                free(patch->def_name);
 998                patch->def_name = s;
 999        }
1000
1001        line += len;
1002        size -= len;
1003        linenr++;
1004        for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1005                static const struct opentry {
1006                        const char *str;
1007                        int (*fn)(const char *, struct patch *);
1008                } optable[] = {
1009                        { "@@ -", gitdiff_hdrend },
1010                        { "--- ", gitdiff_oldname },
1011                        { "+++ ", gitdiff_newname },
1012                        { "old mode ", gitdiff_oldmode },
1013                        { "new mode ", gitdiff_newmode },
1014                        { "deleted file mode ", gitdiff_delete },
1015                        { "new file mode ", gitdiff_newfile },
1016                        { "copy from ", gitdiff_copysrc },
1017                        { "copy to ", gitdiff_copydst },
1018                        { "rename old ", gitdiff_renamesrc },
1019                        { "rename new ", gitdiff_renamedst },
1020                        { "rename from ", gitdiff_renamesrc },
1021                        { "rename to ", gitdiff_renamedst },
1022                        { "similarity index ", gitdiff_similarity },
1023                        { "dissimilarity index ", gitdiff_dissimilarity },
1024                        { "index ", gitdiff_index },
1025                        { "", gitdiff_unrecognized },
1026                };
1027                int i;
1028
1029                len = linelen(line, size);
1030                if (!len || line[len-1] != '\n')
1031                        break;
1032                for (i = 0; i < ARRAY_SIZE(optable); i++) {
1033                        const struct opentry *p = optable + i;
1034                        int oplen = strlen(p->str);
1035                        if (len < oplen || memcmp(p->str, line, oplen))
1036                                continue;
1037                        if (p->fn(line + oplen, patch) < 0)
1038                                return offset;
1039                        break;
1040                }
1041        }
1042
1043        return offset;
1044}
1045
1046static int parse_num(const char *line, unsigned long *p)
1047{
1048        char *ptr;
1049
1050        if (!isdigit(*line))
1051                return 0;
1052        *p = strtoul(line, &ptr, 10);
1053        return ptr - line;
1054}
1055
1056static int parse_range(const char *line, int len, int offset, const char *expect,
1057                       unsigned long *p1, unsigned long *p2)
1058{
1059        int digits, ex;
1060
1061        if (offset < 0 || offset >= len)
1062                return -1;
1063        line += offset;
1064        len -= offset;
1065
1066        digits = parse_num(line, p1);
1067        if (!digits)
1068                return -1;
1069
1070        offset += digits;
1071        line += digits;
1072        len -= digits;
1073
1074        *p2 = 1;
1075        if (*line == ',') {
1076                digits = parse_num(line+1, p2);
1077                if (!digits)
1078                        return -1;
1079
1080                offset += digits+1;
1081                line += digits+1;
1082                len -= digits+1;
1083        }
1084
1085        ex = strlen(expect);
1086        if (ex > len)
1087                return -1;
1088        if (memcmp(line, expect, ex))
1089                return -1;
1090
1091        return offset + ex;
1092}
1093
1094static void recount_diff(char *line, int size, struct fragment *fragment)
1095{
1096        int oldlines = 0, newlines = 0, ret = 0;
1097
1098        if (size < 1) {
1099                warning("recount: ignore empty hunk");
1100                return;
1101        }
1102
1103        for (;;) {
1104                int len = linelen(line, size);
1105                size -= len;
1106                line += len;
1107
1108                if (size < 1)
1109                        break;
1110
1111                switch (*line) {
1112                case ' ': case '\n':
1113                        newlines++;
1114                        /* fall through */
1115                case '-':
1116                        oldlines++;
1117                        continue;
1118                case '+':
1119                        newlines++;
1120                        continue;
1121                case '\\':
1122                        continue;
1123                case '@':
1124                        ret = size < 3 || prefixcmp(line, "@@ ");
1125                        break;
1126                case 'd':
1127                        ret = size < 5 || prefixcmp(line, "diff ");
1128                        break;
1129                default:
1130                        ret = -1;
1131                        break;
1132                }
1133                if (ret) {
1134                        warning("recount: unexpected line: %.*s",
1135                                (int)linelen(line, size), line);
1136                        return;
1137                }
1138                break;
1139        }
1140        fragment->oldlines = oldlines;
1141        fragment->newlines = newlines;
1142}
1143
1144/*
1145 * Parse a unified diff fragment header of the
1146 * form "@@ -a,b +c,d @@"
1147 */
1148static int parse_fragment_header(char *line, int len, struct fragment *fragment)
1149{
1150        int offset;
1151
1152        if (!len || line[len-1] != '\n')
1153                return -1;
1154
1155        /* Figure out the number of lines in a fragment */
1156        offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1157        offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1158
1159        return offset;
1160}
1161
1162static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
1163{
1164        unsigned long offset, len;
1165
1166        patch->is_toplevel_relative = 0;
1167        patch->is_rename = patch->is_copy = 0;
1168        patch->is_new = patch->is_delete = -1;
1169        patch->old_mode = patch->new_mode = 0;
1170        patch->old_name = patch->new_name = NULL;
1171        for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1172                unsigned long nextlen;
1173
1174                len = linelen(line, size);
1175                if (!len)
1176                        break;
1177
1178                /* Testing this early allows us to take a few shortcuts.. */
1179                if (len < 6)
1180                        continue;
1181
1182                /*
1183                 * Make sure we don't find any unconnected patch fragments.
1184                 * That's a sign that we didn't find a header, and that a
1185                 * patch has become corrupted/broken up.
1186                 */
1187                if (!memcmp("@@ -", line, 4)) {
1188                        struct fragment dummy;
1189                        if (parse_fragment_header(line, len, &dummy) < 0)
1190                                continue;
1191                        die("patch fragment without header at line %d: %.*s",
1192                            linenr, (int)len-1, line);
1193                }
1194
1195                if (size < len + 6)
1196                        break;
1197
1198                /*
1199                 * Git patch? It might not have a real patch, just a rename
1200                 * or mode change, so we handle that specially
1201                 */
1202                if (!memcmp("diff --git ", line, 11)) {
1203                        int git_hdr_len = parse_git_header(line, len, size, patch);
1204                        if (git_hdr_len <= len)
1205                                continue;
1206                        if (!patch->old_name && !patch->new_name) {
1207                                if (!patch->def_name)
1208                                        die("git diff header lacks filename information when removing "
1209                                            "%d leading pathname components (line %d)" , p_value, linenr);
1210                                patch->old_name = patch->new_name = patch->def_name;
1211                        }
1212                        patch->is_toplevel_relative = 1;
1213                        *hdrsize = git_hdr_len;
1214                        return offset;
1215                }
1216
1217                /* --- followed by +++ ? */
1218                if (memcmp("--- ", line,  4) || memcmp("+++ ", line + len, 4))
1219                        continue;
1220
1221                /*
1222                 * We only accept unified patches, so we want it to
1223                 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1224                 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1225                 */
1226                nextlen = linelen(line + len, size - len);
1227                if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1228                        continue;
1229
1230                /* Ok, we'll consider it a patch */
1231                parse_traditional_patch(line, line+len, patch);
1232                *hdrsize = len + nextlen;
1233                linenr += 2;
1234                return offset;
1235        }
1236        return -1;
1237}
1238
1239static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1240{
1241        char *err;
1242
1243        if (!result)
1244                return;
1245
1246        whitespace_error++;
1247        if (squelch_whitespace_errors &&
1248            squelch_whitespace_errors < whitespace_error)
1249                return;
1250
1251        err = whitespace_error_string(result);
1252        fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1253                patch_input_file, linenr, err, len, line);
1254        free(err);
1255}
1256
1257static void check_whitespace(const char *line, int len, unsigned ws_rule)
1258{
1259        unsigned result = ws_check(line + 1, len - 1, ws_rule);
1260
1261        record_ws_error(result, line + 1, len - 2, linenr);
1262}
1263
1264/*
1265 * Parse a unified diff. Note that this really needs to parse each
1266 * fragment separately, since the only way to know the difference
1267 * between a "---" that is part of a patch, and a "---" that starts
1268 * the next patch is to look at the line counts..
1269 */
1270static int parse_fragment(char *line, unsigned long size,
1271                          struct patch *patch, struct fragment *fragment)
1272{
1273        int added, deleted;
1274        int len = linelen(line, size), offset;
1275        unsigned long oldlines, newlines;
1276        unsigned long leading, trailing;
1277
1278        offset = parse_fragment_header(line, len, fragment);
1279        if (offset < 0)
1280                return -1;
1281        if (offset > 0 && patch->recount)
1282                recount_diff(line + offset, size - offset, fragment);
1283        oldlines = fragment->oldlines;
1284        newlines = fragment->newlines;
1285        leading = 0;
1286        trailing = 0;
1287
1288        /* Parse the thing.. */
1289        line += len;
1290        size -= len;
1291        linenr++;
1292        added = deleted = 0;
1293        for (offset = len;
1294             0 < size;
1295             offset += len, size -= len, line += len, linenr++) {
1296                if (!oldlines && !newlines)
1297                        break;
1298                len = linelen(line, size);
1299                if (!len || line[len-1] != '\n')
1300                        return -1;
1301                switch (*line) {
1302                default:
1303                        return -1;
1304                case '\n': /* newer GNU diff, an empty context line */
1305                case ' ':
1306                        oldlines--;
1307                        newlines--;
1308                        if (!deleted && !added)
1309                                leading++;
1310                        trailing++;
1311                        break;
1312                case '-':
1313                        if (apply_in_reverse &&
1314                            ws_error_action != nowarn_ws_error)
1315                                check_whitespace(line, len, patch->ws_rule);
1316                        deleted++;
1317                        oldlines--;
1318                        trailing = 0;
1319                        break;
1320                case '+':
1321                        if (!apply_in_reverse &&
1322                            ws_error_action != nowarn_ws_error)
1323                                check_whitespace(line, len, patch->ws_rule);
1324                        added++;
1325                        newlines--;
1326                        trailing = 0;
1327                        break;
1328
1329                /*
1330                 * We allow "\ No newline at end of file". Depending
1331                 * on locale settings when the patch was produced we
1332                 * don't know what this line looks like. The only
1333                 * thing we do know is that it begins with "\ ".
1334                 * Checking for 12 is just for sanity check -- any
1335                 * l10n of "\ No newline..." is at least that long.
1336                 */
1337                case '\\':
1338                        if (len < 12 || memcmp(line, "\\ ", 2))
1339                                return -1;
1340                        break;
1341                }
1342        }
1343        if (oldlines || newlines)
1344                return -1;
1345        fragment->leading = leading;
1346        fragment->trailing = trailing;
1347
1348        /*
1349         * If a fragment ends with an incomplete line, we failed to include
1350         * it in the above loop because we hit oldlines == newlines == 0
1351         * before seeing it.
1352         */
1353        if (12 < size && !memcmp(line, "\\ ", 2))
1354                offset += linelen(line, size);
1355
1356        patch->lines_added += added;
1357        patch->lines_deleted += deleted;
1358
1359        if (0 < patch->is_new && oldlines)
1360                return error("new file depends on old contents");
1361        if (0 < patch->is_delete && newlines)
1362                return error("deleted file still has contents");
1363        return offset;
1364}
1365
1366static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
1367{
1368        unsigned long offset = 0;
1369        unsigned long oldlines = 0, newlines = 0, context = 0;
1370        struct fragment **fragp = &patch->fragments;
1371
1372        while (size > 4 && !memcmp(line, "@@ -", 4)) {
1373                struct fragment *fragment;
1374                int len;
1375
1376                fragment = xcalloc(1, sizeof(*fragment));
1377                fragment->linenr = linenr;
1378                len = parse_fragment(line, size, patch, fragment);
1379                if (len <= 0)
1380                        die("corrupt patch at line %d", linenr);
1381                fragment->patch = line;
1382                fragment->size = len;
1383                oldlines += fragment->oldlines;
1384                newlines += fragment->newlines;
1385                context += fragment->leading + fragment->trailing;
1386
1387                *fragp = fragment;
1388                fragp = &fragment->next;
1389
1390                offset += len;
1391                line += len;
1392                size -= len;
1393        }
1394
1395        /*
1396         * If something was removed (i.e. we have old-lines) it cannot
1397         * be creation, and if something was added it cannot be
1398         * deletion.  However, the reverse is not true; --unified=0
1399         * patches that only add are not necessarily creation even
1400         * though they do not have any old lines, and ones that only
1401         * delete are not necessarily deletion.
1402         *
1403         * Unfortunately, a real creation/deletion patch do _not_ have
1404         * any context line by definition, so we cannot safely tell it
1405         * apart with --unified=0 insanity.  At least if the patch has
1406         * more than one hunk it is not creation or deletion.
1407         */
1408        if (patch->is_new < 0 &&
1409            (oldlines || (patch->fragments && patch->fragments->next)))
1410                patch->is_new = 0;
1411        if (patch->is_delete < 0 &&
1412            (newlines || (patch->fragments && patch->fragments->next)))
1413                patch->is_delete = 0;
1414
1415        if (0 < patch->is_new && oldlines)
1416                die("new file %s depends on old contents", patch->new_name);
1417        if (0 < patch->is_delete && newlines)
1418                die("deleted file %s still has contents", patch->old_name);
1419        if (!patch->is_delete && !newlines && context)
1420                fprintf(stderr, "** warning: file %s becomes empty but "
1421                        "is not deleted\n", patch->new_name);
1422
1423        return offset;
1424}
1425
1426static inline int metadata_changes(struct patch *patch)
1427{
1428        return  patch->is_rename > 0 ||
1429                patch->is_copy > 0 ||
1430                patch->is_new > 0 ||
1431                patch->is_delete ||
1432                (patch->old_mode && patch->new_mode &&
1433                 patch->old_mode != patch->new_mode);
1434}
1435
1436static char *inflate_it(const void *data, unsigned long size,
1437                        unsigned long inflated_size)
1438{
1439        z_stream stream;
1440        void *out;
1441        int st;
1442
1443        memset(&stream, 0, sizeof(stream));
1444
1445        stream.next_in = (unsigned char *)data;
1446        stream.avail_in = size;
1447        stream.next_out = out = xmalloc(inflated_size);
1448        stream.avail_out = inflated_size;
1449        git_inflate_init(&stream);
1450        st = git_inflate(&stream, Z_FINISH);
1451        git_inflate_end(&stream);
1452        if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1453                free(out);
1454                return NULL;
1455        }
1456        return out;
1457}
1458
1459static struct fragment *parse_binary_hunk(char **buf_p,
1460                                          unsigned long *sz_p,
1461                                          int *status_p,
1462                                          int *used_p)
1463{
1464        /*
1465         * Expect a line that begins with binary patch method ("literal"
1466         * or "delta"), followed by the length of data before deflating.
1467         * a sequence of 'length-byte' followed by base-85 encoded data
1468         * should follow, terminated by a newline.
1469         *
1470         * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1471         * and we would limit the patch line to 66 characters,
1472         * so one line can fit up to 13 groups that would decode
1473         * to 52 bytes max.  The length byte 'A'-'Z' corresponds
1474         * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1475         */
1476        int llen, used;
1477        unsigned long size = *sz_p;
1478        char *buffer = *buf_p;
1479        int patch_method;
1480        unsigned long origlen;
1481        char *data = NULL;
1482        int hunk_size = 0;
1483        struct fragment *frag;
1484
1485        llen = linelen(buffer, size);
1486        used = llen;
1487
1488        *status_p = 0;
1489
1490        if (!prefixcmp(buffer, "delta ")) {
1491                patch_method = BINARY_DELTA_DEFLATED;
1492                origlen = strtoul(buffer + 6, NULL, 10);
1493        }
1494        else if (!prefixcmp(buffer, "literal ")) {
1495                patch_method = BINARY_LITERAL_DEFLATED;
1496                origlen = strtoul(buffer + 8, NULL, 10);
1497        }
1498        else
1499                return NULL;
1500
1501        linenr++;
1502        buffer += llen;
1503        while (1) {
1504                int byte_length, max_byte_length, newsize;
1505                llen = linelen(buffer, size);
1506                used += llen;
1507                linenr++;
1508                if (llen == 1) {
1509                        /* consume the blank line */
1510                        buffer++;
1511                        size--;
1512                        break;
1513                }
1514                /*
1515                 * Minimum line is "A00000\n" which is 7-byte long,
1516                 * and the line length must be multiple of 5 plus 2.
1517                 */
1518                if ((llen < 7) || (llen-2) % 5)
1519                        goto corrupt;
1520                max_byte_length = (llen - 2) / 5 * 4;
1521                byte_length = *buffer;
1522                if ('A' <= byte_length && byte_length <= 'Z')
1523                        byte_length = byte_length - 'A' + 1;
1524                else if ('a' <= byte_length && byte_length <= 'z')
1525                        byte_length = byte_length - 'a' + 27;
1526                else
1527                        goto corrupt;
1528                /* if the input length was not multiple of 4, we would
1529                 * have filler at the end but the filler should never
1530                 * exceed 3 bytes
1531                 */
1532                if (max_byte_length < byte_length ||
1533                    byte_length <= max_byte_length - 4)
1534                        goto corrupt;
1535                newsize = hunk_size + byte_length;
1536                data = xrealloc(data, newsize);
1537                if (decode_85(data + hunk_size, buffer + 1, byte_length))
1538                        goto corrupt;
1539                hunk_size = newsize;
1540                buffer += llen;
1541                size -= llen;
1542        }
1543
1544        frag = xcalloc(1, sizeof(*frag));
1545        frag->patch = inflate_it(data, hunk_size, origlen);
1546        if (!frag->patch)
1547                goto corrupt;
1548        free(data);
1549        frag->size = origlen;
1550        *buf_p = buffer;
1551        *sz_p = size;
1552        *used_p = used;
1553        frag->binary_patch_method = patch_method;
1554        return frag;
1555
1556 corrupt:
1557        free(data);
1558        *status_p = -1;
1559        error("corrupt binary patch at line %d: %.*s",
1560              linenr-1, llen-1, buffer);
1561        return NULL;
1562}
1563
1564static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1565{
1566        /*
1567         * We have read "GIT binary patch\n"; what follows is a line
1568         * that says the patch method (currently, either "literal" or
1569         * "delta") and the length of data before deflating; a
1570         * sequence of 'length-byte' followed by base-85 encoded data
1571         * follows.
1572         *
1573         * When a binary patch is reversible, there is another binary
1574         * hunk in the same format, starting with patch method (either
1575         * "literal" or "delta") with the length of data, and a sequence
1576         * of length-byte + base-85 encoded data, terminated with another
1577         * empty line.  This data, when applied to the postimage, produces
1578         * the preimage.
1579         */
1580        struct fragment *forward;
1581        struct fragment *reverse;
1582        int status;
1583        int used, used_1;
1584
1585        forward = parse_binary_hunk(&buffer, &size, &status, &used);
1586        if (!forward && !status)
1587                /* there has to be one hunk (forward hunk) */
1588                return error("unrecognized binary patch at line %d", linenr-1);
1589        if (status)
1590                /* otherwise we already gave an error message */
1591                return status;
1592
1593        reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1594        if (reverse)
1595                used += used_1;
1596        else if (status) {
1597                /*
1598                 * Not having reverse hunk is not an error, but having
1599                 * a corrupt reverse hunk is.
1600                 */
1601                free((void*) forward->patch);
1602                free(forward);
1603                return status;
1604        }
1605        forward->next = reverse;
1606        patch->fragments = forward;
1607        patch->is_binary = 1;
1608        return used;
1609}
1610
1611static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1612{
1613        int hdrsize, patchsize;
1614        int offset = find_header(buffer, size, &hdrsize, patch);
1615
1616        if (offset < 0)
1617                return offset;
1618
1619        patch->ws_rule = whitespace_rule(patch->new_name
1620                                         ? patch->new_name
1621                                         : patch->old_name);
1622
1623        patchsize = parse_single_patch(buffer + offset + hdrsize,
1624                                       size - offset - hdrsize, patch);
1625
1626        if (!patchsize) {
1627                static const char *binhdr[] = {
1628                        "Binary files ",
1629                        "Files ",
1630                        NULL,
1631                };
1632                static const char git_binary[] = "GIT binary patch\n";
1633                int i;
1634                int hd = hdrsize + offset;
1635                unsigned long llen = linelen(buffer + hd, size - hd);
1636
1637                if (llen == sizeof(git_binary) - 1 &&
1638                    !memcmp(git_binary, buffer + hd, llen)) {
1639                        int used;
1640                        linenr++;
1641                        used = parse_binary(buffer + hd + llen,
1642                                            size - hd - llen, patch);
1643                        if (used)
1644                                patchsize = used + llen;
1645                        else
1646                                patchsize = 0;
1647                }
1648                else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1649                        for (i = 0; binhdr[i]; i++) {
1650                                int len = strlen(binhdr[i]);
1651                                if (len < size - hd &&
1652                                    !memcmp(binhdr[i], buffer + hd, len)) {
1653                                        linenr++;
1654                                        patch->is_binary = 1;
1655                                        patchsize = llen;
1656                                        break;
1657                                }
1658                        }
1659                }
1660
1661                /* Empty patch cannot be applied if it is a text patch
1662                 * without metadata change.  A binary patch appears
1663                 * empty to us here.
1664                 */
1665                if ((apply || check) &&
1666                    (!patch->is_binary && !metadata_changes(patch)))
1667                        die("patch with only garbage at line %d", linenr);
1668        }
1669
1670        return offset + hdrsize + patchsize;
1671}
1672
1673#define swap(a,b) myswap((a),(b),sizeof(a))
1674
1675#define myswap(a, b, size) do {         \
1676        unsigned char mytmp[size];      \
1677        memcpy(mytmp, &a, size);                \
1678        memcpy(&a, &b, size);           \
1679        memcpy(&b, mytmp, size);                \
1680} while (0)
1681
1682static void reverse_patches(struct patch *p)
1683{
1684        for (; p; p = p->next) {
1685                struct fragment *frag = p->fragments;
1686
1687                swap(p->new_name, p->old_name);
1688                swap(p->new_mode, p->old_mode);
1689                swap(p->is_new, p->is_delete);
1690                swap(p->lines_added, p->lines_deleted);
1691                swap(p->old_sha1_prefix, p->new_sha1_prefix);
1692
1693                for (; frag; frag = frag->next) {
1694                        swap(frag->newpos, frag->oldpos);
1695                        swap(frag->newlines, frag->oldlines);
1696                }
1697        }
1698}
1699
1700static const char pluses[] =
1701"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1702static const char minuses[]=
1703"----------------------------------------------------------------------";
1704
1705static void show_stats(struct patch *patch)
1706{
1707        struct strbuf qname = STRBUF_INIT;
1708        char *cp = patch->new_name ? patch->new_name : patch->old_name;
1709        int max, add, del;
1710
1711        quote_c_style(cp, &qname, NULL, 0);
1712
1713        /*
1714         * "scale" the filename
1715         */
1716        max = max_len;
1717        if (max > 50)
1718                max = 50;
1719
1720        if (qname.len > max) {
1721                cp = strchr(qname.buf + qname.len + 3 - max, '/');
1722                if (!cp)
1723                        cp = qname.buf + qname.len + 3 - max;
1724                strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
1725        }
1726
1727        if (patch->is_binary) {
1728                printf(" %-*s |  Bin\n", max, qname.buf);
1729                strbuf_release(&qname);
1730                return;
1731        }
1732
1733        printf(" %-*s |", max, qname.buf);
1734        strbuf_release(&qname);
1735
1736        /*
1737         * scale the add/delete
1738         */
1739        max = max + max_change > 70 ? 70 - max : max_change;
1740        add = patch->lines_added;
1741        del = patch->lines_deleted;
1742
1743        if (max_change > 0) {
1744                int total = ((add + del) * max + max_change / 2) / max_change;
1745                add = (add * max + max_change / 2) / max_change;
1746                del = total - add;
1747        }
1748        printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
1749                add, pluses, del, minuses);
1750}
1751
1752static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
1753{
1754        switch (st->st_mode & S_IFMT) {
1755        case S_IFLNK:
1756                if (strbuf_readlink(buf, path, st->st_size) < 0)
1757                        return error("unable to read symlink %s", path);
1758                return 0;
1759        case S_IFREG:
1760                if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
1761                        return error("unable to open or read %s", path);
1762                convert_to_git(path, buf->buf, buf->len, buf, 0);
1763                return 0;
1764        default:
1765                return -1;
1766        }
1767}
1768
1769/*
1770 * Update the preimage, and the common lines in postimage,
1771 * from buffer buf of length len. If postlen is 0 the postimage
1772 * is updated in place, otherwise it's updated on a new buffer
1773 * of length postlen
1774 */
1775
1776static void update_pre_post_images(struct image *preimage,
1777                                   struct image *postimage,
1778                                   char *buf,
1779                                   size_t len, size_t postlen)
1780{
1781        int i, ctx;
1782        char *new, *old, *fixed;
1783        struct image fixed_preimage;
1784
1785        /*
1786         * Update the preimage with whitespace fixes.  Note that we
1787         * are not losing preimage->buf -- apply_one_fragment() will
1788         * free "oldlines".
1789         */
1790        prepare_image(&fixed_preimage, buf, len, 1);
1791        assert(fixed_preimage.nr == preimage->nr);
1792        for (i = 0; i < preimage->nr; i++)
1793                fixed_preimage.line[i].flag = preimage->line[i].flag;
1794        free(preimage->line_allocated);
1795        *preimage = fixed_preimage;
1796
1797        /*
1798         * Adjust the common context lines in postimage. This can be
1799         * done in-place when we are just doing whitespace fixing,
1800         * which does not make the string grow, but needs a new buffer
1801         * when ignoring whitespace causes the update, since in this case
1802         * we could have e.g. tabs converted to multiple spaces.
1803         * We trust the caller to tell us if the update can be done
1804         * in place (postlen==0) or not.
1805         */
1806        old = postimage->buf;
1807        if (postlen)
1808                new = postimage->buf = xmalloc(postlen);
1809        else
1810                new = old;
1811        fixed = preimage->buf;
1812        for (i = ctx = 0; i < postimage->nr; i++) {
1813                size_t len = postimage->line[i].len;
1814                if (!(postimage->line[i].flag & LINE_COMMON)) {
1815                        /* an added line -- no counterparts in preimage */
1816                        memmove(new, old, len);
1817                        old += len;
1818                        new += len;
1819                        continue;
1820                }
1821
1822                /* a common context -- skip it in the original postimage */
1823                old += len;
1824
1825                /* and find the corresponding one in the fixed preimage */
1826                while (ctx < preimage->nr &&
1827                       !(preimage->line[ctx].flag & LINE_COMMON)) {
1828                        fixed += preimage->line[ctx].len;
1829                        ctx++;
1830                }
1831                if (preimage->nr <= ctx)
1832                        die("oops");
1833
1834                /* and copy it in, while fixing the line length */
1835                len = preimage->line[ctx].len;
1836                memcpy(new, fixed, len);
1837                new += len;
1838                fixed += len;
1839                postimage->line[i].len = len;
1840                ctx++;
1841        }
1842
1843        /* Fix the length of the whole thing */
1844        postimage->len = new - postimage->buf;
1845}
1846
1847static int match_fragment(struct image *img,
1848                          struct image *preimage,
1849                          struct image *postimage,
1850                          unsigned long try,
1851                          int try_lno,
1852                          unsigned ws_rule,
1853                          int match_beginning, int match_end)
1854{
1855        int i;
1856        char *fixed_buf, *buf, *orig, *target;
1857        int preimage_limit;
1858
1859        if (preimage->nr + try_lno <= img->nr) {
1860                /*
1861                 * The hunk falls within the boundaries of img.
1862                 */
1863                preimage_limit = preimage->nr;
1864                if (match_end && (preimage->nr + try_lno != img->nr))
1865                        return 0;
1866        } else if (ws_error_action == correct_ws_error &&
1867                   (ws_rule & WS_BLANK_AT_EOF) && match_end) {
1868                /*
1869                 * This hunk that matches at the end extends beyond
1870                 * the end of img, and we are removing blank lines
1871                 * at the end of the file.  This many lines from the
1872                 * beginning of the preimage must match with img, and
1873                 * the remainder of the preimage must be blank.
1874                 */
1875                preimage_limit = img->nr - try_lno;
1876        } else {
1877                /*
1878                 * The hunk extends beyond the end of the img and
1879                 * we are not removing blanks at the end, so we
1880                 * should reject the hunk at this position.
1881                 */
1882                return 0;
1883        }
1884
1885        if (match_beginning && try_lno)
1886                return 0;
1887
1888        /* Quick hash check */
1889        for (i = 0; i < preimage_limit; i++)
1890                if (preimage->line[i].hash != img->line[try_lno + i].hash)
1891                        return 0;
1892
1893        if (preimage_limit == preimage->nr) {
1894                /*
1895                 * Do we have an exact match?  If we were told to match
1896                 * at the end, size must be exactly at try+fragsize,
1897                 * otherwise try+fragsize must be still within the preimage,
1898                 * and either case, the old piece should match the preimage
1899                 * exactly.
1900                 */
1901                if ((match_end
1902                     ? (try + preimage->len == img->len)
1903                     : (try + preimage->len <= img->len)) &&
1904                    !memcmp(img->buf + try, preimage->buf, preimage->len))
1905                        return 1;
1906        } else {
1907                /*
1908                 * The preimage extends beyond the end of img, so
1909                 * there cannot be an exact match.
1910                 *
1911                 * There must be one non-blank context line that match
1912                 * a line before the end of img.
1913                 */
1914                char *buf_end;
1915
1916                buf = preimage->buf;
1917                buf_end = buf;
1918                for (i = 0; i < preimage_limit; i++)
1919                        buf_end += preimage->line[i].len;
1920
1921                for ( ; buf < buf_end; buf++)
1922                        if (!isspace(*buf))
1923                                break;
1924                if (buf == buf_end)
1925                        return 0;
1926        }
1927
1928        /*
1929         * No exact match. If we are ignoring whitespace, run a line-by-line
1930         * fuzzy matching. We collect all the line length information because
1931         * we need it to adjust whitespace if we match.
1932         */
1933        if (ws_ignore_action == ignore_ws_change) {
1934                size_t imgoff = 0;
1935                size_t preoff = 0;
1936                size_t postlen = postimage->len;
1937                size_t extra_chars;
1938                char *preimage_eof;
1939                char *preimage_end;
1940                for (i = 0; i < preimage_limit; i++) {
1941                        size_t prelen = preimage->line[i].len;
1942                        size_t imglen = img->line[try_lno+i].len;
1943
1944                        if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
1945                                              preimage->buf + preoff, prelen))
1946                                return 0;
1947                        if (preimage->line[i].flag & LINE_COMMON)
1948                                postlen += imglen - prelen;
1949                        imgoff += imglen;
1950                        preoff += prelen;
1951                }
1952
1953                /*
1954                 * Ok, the preimage matches with whitespace fuzz.
1955                 *
1956                 * imgoff now holds the true length of the target that
1957                 * matches the preimage before the end of the file.
1958                 *
1959                 * Count the number of characters in the preimage that fall
1960                 * beyond the end of the file and make sure that all of them
1961                 * are whitespace characters. (This can only happen if
1962                 * we are removing blank lines at the end of the file.)
1963                 */
1964                buf = preimage_eof = preimage->buf + preoff;
1965                for ( ; i < preimage->nr; i++)
1966                        preoff += preimage->line[i].len;
1967                preimage_end = preimage->buf + preoff;
1968                for ( ; buf < preimage_end; buf++)
1969                        if (!isspace(*buf))
1970                                return 0;
1971
1972                /*
1973                 * Update the preimage and the common postimage context
1974                 * lines to use the same whitespace as the target.
1975                 * If whitespace is missing in the target (i.e.
1976                 * if the preimage extends beyond the end of the file),
1977                 * use the whitespace from the preimage.
1978                 */
1979                extra_chars = preimage_end - preimage_eof;
1980                fixed_buf = xmalloc(imgoff + extra_chars);
1981                memcpy(fixed_buf, img->buf + try, imgoff);
1982                memcpy(fixed_buf + imgoff, preimage_eof, extra_chars);
1983                imgoff += extra_chars;
1984                update_pre_post_images(preimage, postimage,
1985                                fixed_buf, imgoff, postlen);
1986                return 1;
1987        }
1988
1989        if (ws_error_action != correct_ws_error)
1990                return 0;
1991
1992        /*
1993         * The hunk does not apply byte-by-byte, but the hash says
1994         * it might with whitespace fuzz. We haven't been asked to
1995         * ignore whitespace, we were asked to correct whitespace
1996         * errors, so let's try matching after whitespace correction.
1997         *
1998         * The preimage may extend beyond the end of the file,
1999         * but in this loop we will only handle the part of the
2000         * preimage that falls within the file.
2001         */
2002        fixed_buf = xmalloc(preimage->len + 1);
2003        buf = fixed_buf;
2004        orig = preimage->buf;
2005        target = img->buf + try;
2006        for (i = 0; i < preimage_limit; i++) {
2007                size_t fixlen; /* length after fixing the preimage */
2008                size_t oldlen = preimage->line[i].len;
2009                size_t tgtlen = img->line[try_lno + i].len;
2010                size_t tgtfixlen; /* length after fixing the target line */
2011                char tgtfixbuf[1024], *tgtfix;
2012                int match;
2013
2014                /* Try fixing the line in the preimage */
2015                fixlen = ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);
2016
2017                /* Try fixing the line in the target */
2018                if (sizeof(tgtfixbuf) > tgtlen)
2019                        tgtfix = tgtfixbuf;
2020                else
2021                        tgtfix = xmalloc(tgtlen);
2022                tgtfixlen = ws_fix_copy(tgtfix, target, tgtlen, ws_rule, NULL);
2023
2024                /*
2025                 * If they match, either the preimage was based on
2026                 * a version before our tree fixed whitespace breakage,
2027                 * or we are lacking a whitespace-fix patch the tree
2028                 * the preimage was based on already had (i.e. target
2029                 * has whitespace breakage, the preimage doesn't).
2030                 * In either case, we are fixing the whitespace breakages
2031                 * so we might as well take the fix together with their
2032                 * real change.
2033                 */
2034                match = (tgtfixlen == fixlen && !memcmp(tgtfix, buf, fixlen));
2035
2036                if (tgtfix != tgtfixbuf)
2037                        free(tgtfix);
2038                if (!match)
2039                        goto unmatch_exit;
2040
2041                orig += oldlen;
2042                buf += fixlen;
2043                target += tgtlen;
2044        }
2045
2046
2047        /*
2048         * Now handle the lines in the preimage that falls beyond the
2049         * end of the file (if any). They will only match if they are
2050         * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2051         * false).
2052         */
2053        for ( ; i < preimage->nr; i++) {
2054                size_t fixlen; /* length after fixing the preimage */
2055                size_t oldlen = preimage->line[i].len;
2056                int j;
2057
2058                /* Try fixing the line in the preimage */
2059                fixlen = ws_fix_copy(buf, orig, oldlen, ws_rule, NULL);
2060
2061                for (j = 0; j < fixlen; j++)
2062                        if (!isspace(buf[j]))
2063                                goto unmatch_exit;
2064
2065                orig += oldlen;
2066                buf += fixlen;
2067        }
2068
2069        /*
2070         * Yes, the preimage is based on an older version that still
2071         * has whitespace breakages unfixed, and fixing them makes the
2072         * hunk match.  Update the context lines in the postimage.
2073         */
2074        update_pre_post_images(preimage, postimage,
2075                               fixed_buf, buf - fixed_buf, 0);
2076        return 1;
2077
2078 unmatch_exit:
2079        free(fixed_buf);
2080        return 0;
2081}
2082
2083static int find_pos(struct image *img,
2084                    struct image *preimage,
2085                    struct image *postimage,
2086                    int line,
2087                    unsigned ws_rule,
2088                    int match_beginning, int match_end)
2089{
2090        int i;
2091        unsigned long backwards, forwards, try;
2092        int backwards_lno, forwards_lno, try_lno;
2093
2094        /*
2095         * If match_beginning or match_end is specified, there is no
2096         * point starting from a wrong line that will never match and
2097         * wander around and wait for a match at the specified end.
2098         */
2099        if (match_beginning)
2100                line = 0;
2101        else if (match_end)
2102                line = img->nr - preimage->nr;
2103
2104        /*
2105         * Because the comparison is unsigned, the following test
2106         * will also take care of a negative line number that can
2107         * result when match_end and preimage is larger than the target.
2108         */
2109        if ((size_t) line > img->nr)
2110                line = img->nr;
2111
2112        try = 0;
2113        for (i = 0; i < line; i++)
2114                try += img->line[i].len;
2115
2116        /*
2117         * There's probably some smart way to do this, but I'll leave
2118         * that to the smart and beautiful people. I'm simple and stupid.
2119         */
2120        backwards = try;
2121        backwards_lno = line;
2122        forwards = try;
2123        forwards_lno = line;
2124        try_lno = line;
2125
2126        for (i = 0; ; i++) {
2127                if (match_fragment(img, preimage, postimage,
2128                                   try, try_lno, ws_rule,
2129                                   match_beginning, match_end))
2130                        return try_lno;
2131
2132        again:
2133                if (backwards_lno == 0 && forwards_lno == img->nr)
2134                        break;
2135
2136                if (i & 1) {
2137                        if (backwards_lno == 0) {
2138                                i++;
2139                                goto again;
2140                        }
2141                        backwards_lno--;
2142                        backwards -= img->line[backwards_lno].len;
2143                        try = backwards;
2144                        try_lno = backwards_lno;
2145                } else {
2146                        if (forwards_lno == img->nr) {
2147                                i++;
2148                                goto again;
2149                        }
2150                        forwards += img->line[forwards_lno].len;
2151                        forwards_lno++;
2152                        try = forwards;
2153                        try_lno = forwards_lno;
2154                }
2155
2156        }
2157        return -1;
2158}
2159
2160static void remove_first_line(struct image *img)
2161{
2162        img->buf += img->line[0].len;
2163        img->len -= img->line[0].len;
2164        img->line++;
2165        img->nr--;
2166}
2167
2168static void remove_last_line(struct image *img)
2169{
2170        img->len -= img->line[--img->nr].len;
2171}
2172
2173static void update_image(struct image *img,
2174                         int applied_pos,
2175                         struct image *preimage,
2176                         struct image *postimage)
2177{
2178        /*
2179         * remove the copy of preimage at offset in img
2180         * and replace it with postimage
2181         */
2182        int i, nr;
2183        size_t remove_count, insert_count, applied_at = 0;
2184        char *result;
2185        int preimage_limit;
2186
2187        /*
2188         * If we are removing blank lines at the end of img,
2189         * the preimage may extend beyond the end.
2190         * If that is the case, we must be careful only to
2191         * remove the part of the preimage that falls within
2192         * the boundaries of img. Initialize preimage_limit
2193         * to the number of lines in the preimage that falls
2194         * within the boundaries.
2195         */
2196        preimage_limit = preimage->nr;
2197        if (preimage_limit > img->nr - applied_pos)
2198                preimage_limit = img->nr - applied_pos;
2199
2200        for (i = 0; i < applied_pos; i++)
2201                applied_at += img->line[i].len;
2202
2203        remove_count = 0;
2204        for (i = 0; i < preimage_limit; i++)
2205                remove_count += img->line[applied_pos + i].len;
2206        insert_count = postimage->len;
2207
2208        /* Adjust the contents */
2209        result = xmalloc(img->len + insert_count - remove_count + 1);
2210        memcpy(result, img->buf, applied_at);
2211        memcpy(result + applied_at, postimage->buf, postimage->len);
2212        memcpy(result + applied_at + postimage->len,
2213               img->buf + (applied_at + remove_count),
2214               img->len - (applied_at + remove_count));
2215        free(img->buf);
2216        img->buf = result;
2217        img->len += insert_count - remove_count;
2218        result[img->len] = '\0';
2219
2220        /* Adjust the line table */
2221        nr = img->nr + postimage->nr - preimage_limit;
2222        if (preimage_limit < postimage->nr) {
2223                /*
2224                 * NOTE: this knows that we never call remove_first_line()
2225                 * on anything other than pre/post image.
2226                 */
2227                img->line = xrealloc(img->line, nr * sizeof(*img->line));
2228                img->line_allocated = img->line;
2229        }
2230        if (preimage_limit != postimage->nr)
2231                memmove(img->line + applied_pos + postimage->nr,
2232                        img->line + applied_pos + preimage_limit,
2233                        (img->nr - (applied_pos + preimage_limit)) *
2234                        sizeof(*img->line));
2235        memcpy(img->line + applied_pos,
2236               postimage->line,
2237               postimage->nr * sizeof(*img->line));
2238        img->nr = nr;
2239}
2240
2241static int apply_one_fragment(struct image *img, struct fragment *frag,
2242                              int inaccurate_eof, unsigned ws_rule)
2243{
2244        int match_beginning, match_end;
2245        const char *patch = frag->patch;
2246        int size = frag->size;
2247        char *old, *new, *oldlines, *newlines;
2248        int new_blank_lines_at_end = 0;
2249        unsigned long leading, trailing;
2250        int pos, applied_pos;
2251        struct image preimage;
2252        struct image postimage;
2253
2254        memset(&preimage, 0, sizeof(preimage));
2255        memset(&postimage, 0, sizeof(postimage));
2256        oldlines = xmalloc(size);
2257        newlines = xmalloc(size);
2258
2259        old = oldlines;
2260        new = newlines;
2261        while (size > 0) {
2262                char first;
2263                int len = linelen(patch, size);
2264                int plen, added;
2265                int added_blank_line = 0;
2266                int is_blank_context = 0;
2267
2268                if (!len)
2269                        break;
2270
2271                /*
2272                 * "plen" is how much of the line we should use for
2273                 * the actual patch data. Normally we just remove the
2274                 * first character on the line, but if the line is
2275                 * followed by "\ No newline", then we also remove the
2276                 * last one (which is the newline, of course).
2277                 */
2278                plen = len - 1;
2279                if (len < size && patch[len] == '\\')
2280                        plen--;
2281                first = *patch;
2282                if (apply_in_reverse) {
2283                        if (first == '-')
2284                                first = '+';
2285                        else if (first == '+')
2286                                first = '-';
2287                }
2288
2289                switch (first) {
2290                case '\n':
2291                        /* Newer GNU diff, empty context line */
2292                        if (plen < 0)
2293                                /* ... followed by '\No newline'; nothing */
2294                                break;
2295                        *old++ = '\n';
2296                        *new++ = '\n';
2297                        add_line_info(&preimage, "\n", 1, LINE_COMMON);
2298                        add_line_info(&postimage, "\n", 1, LINE_COMMON);
2299                        is_blank_context = 1;
2300                        break;
2301                case ' ':
2302                        if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2303                            ws_blank_line(patch + 1, plen, ws_rule))
2304                                is_blank_context = 1;
2305                case '-':
2306                        memcpy(old, patch + 1, plen);
2307                        add_line_info(&preimage, old, plen,
2308                                      (first == ' ' ? LINE_COMMON : 0));
2309                        old += plen;
2310                        if (first == '-')
2311                                break;
2312                /* Fall-through for ' ' */
2313                case '+':
2314                        /* --no-add does not add new lines */
2315                        if (first == '+' && no_add)
2316                                break;
2317
2318                        if (first != '+' ||
2319                            !whitespace_error ||
2320                            ws_error_action != correct_ws_error) {
2321                                memcpy(new, patch + 1, plen);
2322                                added = plen;
2323                        }
2324                        else {
2325                                added = ws_fix_copy(new, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2326                        }
2327                        add_line_info(&postimage, new, added,
2328                                      (first == '+' ? 0 : LINE_COMMON));
2329                        new += added;
2330                        if (first == '+' &&
2331                            (ws_rule & WS_BLANK_AT_EOF) &&
2332                            ws_blank_line(patch + 1, plen, ws_rule))
2333                                added_blank_line = 1;
2334                        break;
2335                case '@': case '\\':
2336                        /* Ignore it, we already handled it */
2337                        break;
2338                default:
2339                        if (apply_verbosely)
2340                                error("invalid start of line: '%c'", first);
2341                        return -1;
2342                }
2343                if (added_blank_line)
2344                        new_blank_lines_at_end++;
2345                else if (is_blank_context)
2346                        ;
2347                else
2348                        new_blank_lines_at_end = 0;
2349                patch += len;
2350                size -= len;
2351        }
2352        if (inaccurate_eof &&
2353            old > oldlines && old[-1] == '\n' &&
2354            new > newlines && new[-1] == '\n') {
2355                old--;
2356                new--;
2357        }
2358
2359        leading = frag->leading;
2360        trailing = frag->trailing;
2361
2362        /*
2363         * A hunk to change lines at the beginning would begin with
2364         * @@ -1,L +N,M @@
2365         * but we need to be careful.  -U0 that inserts before the second
2366         * line also has this pattern.
2367         *
2368         * And a hunk to add to an empty file would begin with
2369         * @@ -0,0 +N,M @@
2370         *
2371         * In other words, a hunk that is (frag->oldpos <= 1) with or
2372         * without leading context must match at the beginning.
2373         */
2374        match_beginning = (!frag->oldpos ||
2375                           (frag->oldpos == 1 && !unidiff_zero));
2376
2377        /*
2378         * A hunk without trailing lines must match at the end.
2379         * However, we simply cannot tell if a hunk must match end
2380         * from the lack of trailing lines if the patch was generated
2381         * with unidiff without any context.
2382         */
2383        match_end = !unidiff_zero && !trailing;
2384
2385        pos = frag->newpos ? (frag->newpos - 1) : 0;
2386        preimage.buf = oldlines;
2387        preimage.len = old - oldlines;
2388        postimage.buf = newlines;
2389        postimage.len = new - newlines;
2390        preimage.line = preimage.line_allocated;
2391        postimage.line = postimage.line_allocated;
2392
2393        for (;;) {
2394
2395                applied_pos = find_pos(img, &preimage, &postimage, pos,
2396                                       ws_rule, match_beginning, match_end);
2397
2398                if (applied_pos >= 0)
2399                        break;
2400
2401                /* Am I at my context limits? */
2402                if ((leading <= p_context) && (trailing <= p_context))
2403                        break;
2404                if (match_beginning || match_end) {
2405                        match_beginning = match_end = 0;
2406                        continue;
2407                }
2408
2409                /*
2410                 * Reduce the number of context lines; reduce both
2411                 * leading and trailing if they are equal otherwise
2412                 * just reduce the larger context.
2413                 */
2414                if (leading >= trailing) {
2415                        remove_first_line(&preimage);
2416                        remove_first_line(&postimage);
2417                        pos--;
2418                        leading--;
2419                }
2420                if (trailing > leading) {
2421                        remove_last_line(&preimage);
2422                        remove_last_line(&postimage);
2423                        trailing--;
2424                }
2425        }
2426
2427        if (applied_pos >= 0) {
2428                if (new_blank_lines_at_end &&
2429                    preimage.nr + applied_pos >= img->nr &&
2430                    (ws_rule & WS_BLANK_AT_EOF) &&
2431                    ws_error_action != nowarn_ws_error) {
2432                        record_ws_error(WS_BLANK_AT_EOF, "+", 1, frag->linenr);
2433                        if (ws_error_action == correct_ws_error) {
2434                                while (new_blank_lines_at_end--)
2435                                        remove_last_line(&postimage);
2436                        }
2437                        /*
2438                         * We would want to prevent write_out_results()
2439                         * from taking place in apply_patch() that follows
2440                         * the callchain led us here, which is:
2441                         * apply_patch->check_patch_list->check_patch->
2442                         * apply_data->apply_fragments->apply_one_fragment
2443                         */
2444                        if (ws_error_action == die_on_ws_error)
2445                                apply = 0;
2446                }
2447
2448                /*
2449                 * Warn if it was necessary to reduce the number
2450                 * of context lines.
2451                 */
2452                if ((leading != frag->leading) ||
2453                    (trailing != frag->trailing))
2454                        fprintf(stderr, "Context reduced to (%ld/%ld)"
2455                                " to apply fragment at %d\n",
2456                                leading, trailing, applied_pos+1);
2457                update_image(img, applied_pos, &preimage, &postimage);
2458        } else {
2459                if (apply_verbosely)
2460                        error("while searching for:\n%.*s",
2461                              (int)(old - oldlines), oldlines);
2462        }
2463
2464        free(oldlines);
2465        free(newlines);
2466        free(preimage.line_allocated);
2467        free(postimage.line_allocated);
2468
2469        return (applied_pos < 0);
2470}
2471
2472static int apply_binary_fragment(struct image *img, struct patch *patch)
2473{
2474        struct fragment *fragment = patch->fragments;
2475        unsigned long len;
2476        void *dst;
2477
2478        /* Binary patch is irreversible without the optional second hunk */
2479        if (apply_in_reverse) {
2480                if (!fragment->next)
2481                        return error("cannot reverse-apply a binary patch "
2482                                     "without the reverse hunk to '%s'",
2483                                     patch->new_name
2484                                     ? patch->new_name : patch->old_name);
2485                fragment = fragment->next;
2486        }
2487        switch (fragment->binary_patch_method) {
2488        case BINARY_DELTA_DEFLATED:
2489                dst = patch_delta(img->buf, img->len, fragment->patch,
2490                                  fragment->size, &len);
2491                if (!dst)
2492                        return -1;
2493                clear_image(img);
2494                img->buf = dst;
2495                img->len = len;
2496                return 0;
2497        case BINARY_LITERAL_DEFLATED:
2498                clear_image(img);
2499                img->len = fragment->size;
2500                img->buf = xmalloc(img->len+1);
2501                memcpy(img->buf, fragment->patch, img->len);
2502                img->buf[img->len] = '\0';
2503                return 0;
2504        }
2505        return -1;
2506}
2507
2508static int apply_binary(struct image *img, struct patch *patch)
2509{
2510        const char *name = patch->old_name ? patch->old_name : patch->new_name;
2511        unsigned char sha1[20];
2512
2513        /*
2514         * For safety, we require patch index line to contain
2515         * full 40-byte textual SHA1 for old and new, at least for now.
2516         */
2517        if (strlen(patch->old_sha1_prefix) != 40 ||
2518            strlen(patch->new_sha1_prefix) != 40 ||
2519            get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2520            get_sha1_hex(patch->new_sha1_prefix, sha1))
2521                return error("cannot apply binary patch to '%s' "
2522                             "without full index line", name);
2523
2524        if (patch->old_name) {
2525                /*
2526                 * See if the old one matches what the patch
2527                 * applies to.
2528                 */
2529                hash_sha1_file(img->buf, img->len, blob_type, sha1);
2530                if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2531                        return error("the patch applies to '%s' (%s), "
2532                                     "which does not match the "
2533                                     "current contents.",
2534                                     name, sha1_to_hex(sha1));
2535        }
2536        else {
2537                /* Otherwise, the old one must be empty. */
2538                if (img->len)
2539                        return error("the patch applies to an empty "
2540                                     "'%s' but it is not empty", name);
2541        }
2542
2543        get_sha1_hex(patch->new_sha1_prefix, sha1);
2544        if (is_null_sha1(sha1)) {
2545                clear_image(img);
2546                return 0; /* deletion patch */
2547        }
2548
2549        if (has_sha1_file(sha1)) {
2550                /* We already have the postimage */
2551                enum object_type type;
2552                unsigned long size;
2553                char *result;
2554
2555                result = read_sha1_file(sha1, &type, &size);
2556                if (!result)
2557                        return error("the necessary postimage %s for "
2558                                     "'%s' cannot be read",
2559                                     patch->new_sha1_prefix, name);
2560                clear_image(img);
2561                img->buf = result;
2562                img->len = size;
2563        } else {
2564                /*
2565                 * We have verified buf matches the preimage;
2566                 * apply the patch data to it, which is stored
2567                 * in the patch->fragments->{patch,size}.
2568                 */
2569                if (apply_binary_fragment(img, patch))
2570                        return error("binary patch does not apply to '%s'",
2571                                     name);
2572
2573                /* verify that the result matches */
2574                hash_sha1_file(img->buf, img->len, blob_type, sha1);
2575                if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2576                        return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2577                                name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2578        }
2579
2580        return 0;
2581}
2582
2583static int apply_fragments(struct image *img, struct patch *patch)
2584{
2585        struct fragment *frag = patch->fragments;
2586        const char *name = patch->old_name ? patch->old_name : patch->new_name;
2587        unsigned ws_rule = patch->ws_rule;
2588        unsigned inaccurate_eof = patch->inaccurate_eof;
2589
2590        if (patch->is_binary)
2591                return apply_binary(img, patch);
2592
2593        while (frag) {
2594                if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {
2595                        error("patch failed: %s:%ld", name, frag->oldpos);
2596                        if (!apply_with_reject)
2597                                return -1;
2598                        frag->rejected = 1;
2599                }
2600                frag = frag->next;
2601        }
2602        return 0;
2603}
2604
2605static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2606{
2607        if (!ce)
2608                return 0;
2609
2610        if (S_ISGITLINK(ce->ce_mode)) {
2611                strbuf_grow(buf, 100);
2612                strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
2613        } else {
2614                enum object_type type;
2615                unsigned long sz;
2616                char *result;
2617
2618                result = read_sha1_file(ce->sha1, &type, &sz);
2619                if (!result)
2620                        return -1;
2621                /* XXX read_sha1_file NUL-terminates */
2622                strbuf_attach(buf, result, sz, sz + 1);
2623        }
2624        return 0;
2625}
2626
2627static struct patch *in_fn_table(const char *name)
2628{
2629        struct string_list_item *item;
2630
2631        if (name == NULL)
2632                return NULL;
2633
2634        item = string_list_lookup(name, &fn_table);
2635        if (item != NULL)
2636                return (struct patch *)item->util;
2637
2638        return NULL;
2639}
2640
2641/*
2642 * item->util in the filename table records the status of the path.
2643 * Usually it points at a patch (whose result records the contents
2644 * of it after applying it), but it could be PATH_WAS_DELETED for a
2645 * path that a previously applied patch has already removed.
2646 */
2647 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2648#define PATH_WAS_DELETED ((struct patch *) -1)
2649
2650static int to_be_deleted(struct patch *patch)
2651{
2652        return patch == PATH_TO_BE_DELETED;
2653}
2654
2655static int was_deleted(struct patch *patch)
2656{
2657        return patch == PATH_WAS_DELETED;
2658}
2659
2660static void add_to_fn_table(struct patch *patch)
2661{
2662        struct string_list_item *item;
2663
2664        /*
2665         * Always add new_name unless patch is a deletion
2666         * This should cover the cases for normal diffs,
2667         * file creations and copies
2668         */
2669        if (patch->new_name != NULL) {
2670                item = string_list_insert(patch->new_name, &fn_table);
2671                item->util = patch;
2672        }
2673
2674        /*
2675         * store a failure on rename/deletion cases because
2676         * later chunks shouldn't patch old names
2677         */
2678        if ((patch->new_name == NULL) || (patch->is_rename)) {
2679                item = string_list_insert(patch->old_name, &fn_table);
2680                item->util = PATH_WAS_DELETED;
2681        }
2682}
2683
2684static void prepare_fn_table(struct patch *patch)
2685{
2686        /*
2687         * store information about incoming file deletion
2688         */
2689        while (patch) {
2690                if ((patch->new_name == NULL) || (patch->is_rename)) {
2691                        struct string_list_item *item;
2692                        item = string_list_insert(patch->old_name, &fn_table);
2693                        item->util = PATH_TO_BE_DELETED;
2694                }
2695                patch = patch->next;
2696        }
2697}
2698
2699static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
2700{
2701        struct strbuf buf = STRBUF_INIT;
2702        struct image image;
2703        size_t len;
2704        char *img;
2705        struct patch *tpatch;
2706
2707        if (!(patch->is_copy || patch->is_rename) &&
2708            (tpatch = in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {
2709                if (was_deleted(tpatch)) {
2710                        return error("patch %s has been renamed/deleted",
2711                                patch->old_name);
2712                }
2713                /* We have a patched copy in memory use that */
2714                strbuf_add(&buf, tpatch->result, tpatch->resultsize);
2715        } else if (cached) {
2716                if (read_file_or_gitlink(ce, &buf))
2717                        return error("read of %s failed", patch->old_name);
2718        } else if (patch->old_name) {
2719                if (S_ISGITLINK(patch->old_mode)) {
2720                        if (ce) {
2721                                read_file_or_gitlink(ce, &buf);
2722                        } else {
2723                                /*
2724                                 * There is no way to apply subproject
2725                                 * patch without looking at the index.
2726                                 */
2727                                patch->fragments = NULL;
2728                        }
2729                } else {
2730                        if (read_old_data(st, patch->old_name, &buf))
2731                                return error("read of %s failed", patch->old_name);
2732                }
2733        }
2734
2735        img = strbuf_detach(&buf, &len);
2736        prepare_image(&image, img, len, !patch->is_binary);
2737
2738        if (apply_fragments(&image, patch) < 0)
2739                return -1; /* note with --reject this succeeds. */
2740        patch->result = image.buf;
2741        patch->resultsize = image.len;
2742        add_to_fn_table(patch);
2743        free(image.line_allocated);
2744
2745        if (0 < patch->is_delete && patch->resultsize)
2746                return error("removal patch leaves file contents");
2747
2748        return 0;
2749}
2750
2751static int check_to_create_blob(const char *new_name, int ok_if_exists)
2752{
2753        struct stat nst;
2754        if (!lstat(new_name, &nst)) {
2755                if (S_ISDIR(nst.st_mode) || ok_if_exists)
2756                        return 0;
2757                /*
2758                 * A leading component of new_name might be a symlink
2759                 * that is going to be removed with this patch, but
2760                 * still pointing at somewhere that has the path.
2761                 * In such a case, path "new_name" does not exist as
2762                 * far as git is concerned.
2763                 */
2764                if (has_symlink_leading_path(new_name, strlen(new_name)))
2765                        return 0;
2766
2767                return error("%s: already exists in working directory", new_name);
2768        }
2769        else if ((errno != ENOENT) && (errno != ENOTDIR))
2770                return error("%s: %s", new_name, strerror(errno));
2771        return 0;
2772}
2773
2774static int verify_index_match(struct cache_entry *ce, struct stat *st)
2775{
2776        if (S_ISGITLINK(ce->ce_mode)) {
2777                if (!S_ISDIR(st->st_mode))
2778                        return -1;
2779                return 0;
2780        }
2781        return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
2782}
2783
2784static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
2785{
2786        const char *old_name = patch->old_name;
2787        struct patch *tpatch = NULL;
2788        int stat_ret = 0;
2789        unsigned st_mode = 0;
2790
2791        /*
2792         * Make sure that we do not have local modifications from the
2793         * index when we are looking at the index.  Also make sure
2794         * we have the preimage file to be patched in the work tree,
2795         * unless --cached, which tells git to apply only in the index.
2796         */
2797        if (!old_name)
2798                return 0;
2799
2800        assert(patch->is_new <= 0);
2801
2802        if (!(patch->is_copy || patch->is_rename) &&
2803            (tpatch = in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {
2804                if (was_deleted(tpatch))
2805                        return error("%s: has been deleted/renamed", old_name);
2806                st_mode = tpatch->new_mode;
2807        } else if (!cached) {
2808                stat_ret = lstat(old_name, st);
2809                if (stat_ret && errno != ENOENT)
2810                        return error("%s: %s", old_name, strerror(errno));
2811        }
2812
2813        if (to_be_deleted(tpatch))
2814                tpatch = NULL;
2815
2816        if (check_index && !tpatch) {
2817                int pos = cache_name_pos(old_name, strlen(old_name));
2818                if (pos < 0) {
2819                        if (patch->is_new < 0)
2820                                goto is_new;
2821                        return error("%s: does not exist in index", old_name);
2822                }
2823                *ce = active_cache[pos];
2824                if (stat_ret < 0) {
2825                        struct checkout costate;
2826                        /* checkout */
2827                        memset(&costate, 0, sizeof(costate));
2828                        costate.base_dir = "";
2829                        costate.refresh_cache = 1;
2830                        if (checkout_entry(*ce, &costate, NULL) ||
2831                            lstat(old_name, st))
2832                                return -1;
2833                }
2834                if (!cached && verify_index_match(*ce, st))
2835                        return error("%s: does not match index", old_name);
2836                if (cached)
2837                        st_mode = (*ce)->ce_mode;
2838        } else if (stat_ret < 0) {
2839                if (patch->is_new < 0)
2840                        goto is_new;
2841                return error("%s: %s", old_name, strerror(errno));
2842        }
2843
2844        if (!cached && !tpatch)
2845                st_mode = ce_mode_from_stat(*ce, st->st_mode);
2846
2847        if (patch->is_new < 0)
2848                patch->is_new = 0;
2849        if (!patch->old_mode)
2850                patch->old_mode = st_mode;
2851        if ((st_mode ^ patch->old_mode) & S_IFMT)
2852                return error("%s: wrong type", old_name);
2853        if (st_mode != patch->old_mode)
2854                warning("%s has type %o, expected %o",
2855                        old_name, st_mode, patch->old_mode);
2856        if (!patch->new_mode && !patch->is_delete)
2857                patch->new_mode = st_mode;
2858        return 0;
2859
2860 is_new:
2861        patch->is_new = 1;
2862        patch->is_delete = 0;
2863        patch->old_name = NULL;
2864        return 0;
2865}
2866
2867static int check_patch(struct patch *patch)
2868{
2869        struct stat st;
2870        const char *old_name = patch->old_name;
2871        const char *new_name = patch->new_name;
2872        const char *name = old_name ? old_name : new_name;
2873        struct cache_entry *ce = NULL;
2874        struct patch *tpatch;
2875        int ok_if_exists;
2876        int status;
2877
2878        patch->rejected = 1; /* we will drop this after we succeed */
2879
2880        status = check_preimage(patch, &ce, &st);
2881        if (status)
2882                return status;
2883        old_name = patch->old_name;
2884
2885        if ((tpatch = in_fn_table(new_name)) &&
2886                        (was_deleted(tpatch) || to_be_deleted(tpatch)))
2887                /*
2888                 * A type-change diff is always split into a patch to
2889                 * delete old, immediately followed by a patch to
2890                 * create new (see diff.c::run_diff()); in such a case
2891                 * it is Ok that the entry to be deleted by the
2892                 * previous patch is still in the working tree and in
2893                 * the index.
2894                 */
2895                ok_if_exists = 1;
2896        else
2897                ok_if_exists = 0;
2898
2899        if (new_name &&
2900            ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
2901                if (check_index &&
2902                    cache_name_pos(new_name, strlen(new_name)) >= 0 &&
2903                    !ok_if_exists)
2904                        return error("%s: already exists in index", new_name);
2905                if (!cached) {
2906                        int err = check_to_create_blob(new_name, ok_if_exists);
2907                        if (err)
2908                                return err;
2909                }
2910                if (!patch->new_mode) {
2911                        if (0 < patch->is_new)
2912                                patch->new_mode = S_IFREG | 0644;
2913                        else
2914                                patch->new_mode = patch->old_mode;
2915                }
2916        }
2917
2918        if (new_name && old_name) {
2919                int same = !strcmp(old_name, new_name);
2920                if (!patch->new_mode)
2921                        patch->new_mode = patch->old_mode;
2922                if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
2923                        return error("new mode (%o) of %s does not match old mode (%o)%s%s",
2924                                patch->new_mode, new_name, patch->old_mode,
2925                                same ? "" : " of ", same ? "" : old_name);
2926        }
2927
2928        if (apply_data(patch, &st, ce) < 0)
2929                return error("%s: patch does not apply", name);
2930        patch->rejected = 0;
2931        return 0;
2932}
2933
2934static int check_patch_list(struct patch *patch)
2935{
2936        int err = 0;
2937
2938        prepare_fn_table(patch);
2939        while (patch) {
2940                if (apply_verbosely)
2941                        say_patch_name(stderr,
2942                                       "Checking patch ", patch, "...\n");
2943                err |= check_patch(patch);
2944                patch = patch->next;
2945        }
2946        return err;
2947}
2948
2949/* This function tries to read the sha1 from the current index */
2950static int get_current_sha1(const char *path, unsigned char *sha1)
2951{
2952        int pos;
2953
2954        if (read_cache() < 0)
2955                return -1;
2956        pos = cache_name_pos(path, strlen(path));
2957        if (pos < 0)
2958                return -1;
2959        hashcpy(sha1, active_cache[pos]->sha1);
2960        return 0;
2961}
2962
2963/* Build an index that contains the just the files needed for a 3way merge */
2964static void build_fake_ancestor(struct patch *list, const char *filename)
2965{
2966        struct patch *patch;
2967        struct index_state result = { NULL };
2968        int fd;
2969
2970        /* Once we start supporting the reverse patch, it may be
2971         * worth showing the new sha1 prefix, but until then...
2972         */
2973        for (patch = list; patch; patch = patch->next) {
2974                const unsigned char *sha1_ptr;
2975                unsigned char sha1[20];
2976                struct cache_entry *ce;
2977                const char *name;
2978
2979                name = patch->old_name ? patch->old_name : patch->new_name;
2980                if (0 < patch->is_new)
2981                        continue;
2982                else if (get_sha1(patch->old_sha1_prefix, sha1))
2983                        /* git diff has no index line for mode/type changes */
2984                        if (!patch->lines_added && !patch->lines_deleted) {
2985                                if (get_current_sha1(patch->new_name, sha1) ||
2986                                    get_current_sha1(patch->old_name, sha1))
2987                                        die("mode change for %s, which is not "
2988                                                "in current HEAD", name);
2989                                sha1_ptr = sha1;
2990                        } else
2991                                die("sha1 information is lacking or useless "
2992                                        "(%s).", name);
2993                else
2994                        sha1_ptr = sha1;
2995
2996                ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
2997                if (!ce)
2998                        die("make_cache_entry failed for path '%s'", name);
2999                if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3000                        die ("Could not add %s to temporary index", name);
3001        }
3002
3003        fd = open(filename, O_WRONLY | O_CREAT, 0666);
3004        if (fd < 0 || write_index(&result, fd) || close(fd))
3005                die ("Could not write temporary index to %s", filename);
3006
3007        discard_index(&result);
3008}
3009
3010static void stat_patch_list(struct patch *patch)
3011{
3012        int files, adds, dels;
3013
3014        for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3015                files++;
3016                adds += patch->lines_added;
3017                dels += patch->lines_deleted;
3018                show_stats(patch);
3019        }
3020
3021        printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
3022}
3023
3024static void numstat_patch_list(struct patch *patch)
3025{
3026        for ( ; patch; patch = patch->next) {
3027                const char *name;
3028                name = patch->new_name ? patch->new_name : patch->old_name;
3029                if (patch->is_binary)
3030                        printf("-\t-\t");
3031                else
3032                        printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3033                write_name_quoted(name, stdout, line_termination);
3034        }
3035}
3036
3037static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3038{
3039        if (mode)
3040                printf(" %s mode %06o %s\n", newdelete, mode, name);
3041        else
3042                printf(" %s %s\n", newdelete, name);
3043}
3044
3045static void show_mode_change(struct patch *p, int show_name)
3046{
3047        if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3048                if (show_name)
3049                        printf(" mode change %06o => %06o %s\n",
3050                               p->old_mode, p->new_mode, p->new_name);
3051                else
3052                        printf(" mode change %06o => %06o\n",
3053                               p->old_mode, p->new_mode);
3054        }
3055}
3056
3057static void show_rename_copy(struct patch *p)
3058{
3059        const char *renamecopy = p->is_rename ? "rename" : "copy";
3060        const char *old, *new;
3061
3062        /* Find common prefix */
3063        old = p->old_name;
3064        new = p->new_name;
3065        while (1) {
3066                const char *slash_old, *slash_new;
3067                slash_old = strchr(old, '/');
3068                slash_new = strchr(new, '/');
3069                if (!slash_old ||
3070                    !slash_new ||
3071                    slash_old - old != slash_new - new ||
3072                    memcmp(old, new, slash_new - new))
3073                        break;
3074                old = slash_old + 1;
3075                new = slash_new + 1;
3076        }
3077        /* p->old_name thru old is the common prefix, and old and new
3078         * through the end of names are renames
3079         */
3080        if (old != p->old_name)
3081                printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3082                       (int)(old - p->old_name), p->old_name,
3083                       old, new, p->score);
3084        else
3085                printf(" %s %s => %s (%d%%)\n", renamecopy,
3086                       p->old_name, p->new_name, p->score);
3087        show_mode_change(p, 0);
3088}
3089
3090static void summary_patch_list(struct patch *patch)
3091{
3092        struct patch *p;
3093
3094        for (p = patch; p; p = p->next) {
3095                if (p->is_new)
3096                        show_file_mode_name("create", p->new_mode, p->new_name);
3097                else if (p->is_delete)
3098                        show_file_mode_name("delete", p->old_mode, p->old_name);
3099                else {
3100                        if (p->is_rename || p->is_copy)
3101                                show_rename_copy(p);
3102                        else {
3103                                if (p->score) {
3104                                        printf(" rewrite %s (%d%%)\n",
3105                                               p->new_name, p->score);
3106                                        show_mode_change(p, 0);
3107                                }
3108                                else
3109                                        show_mode_change(p, 1);
3110                        }
3111                }
3112        }
3113}
3114
3115static void patch_stats(struct patch *patch)
3116{
3117        int lines = patch->lines_added + patch->lines_deleted;
3118
3119        if (lines > max_change)
3120                max_change = lines;
3121        if (patch->old_name) {
3122                int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3123                if (!len)
3124                        len = strlen(patch->old_name);
3125                if (len > max_len)
3126                        max_len = len;
3127        }
3128        if (patch->new_name) {
3129                int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3130                if (!len)
3131                        len = strlen(patch->new_name);
3132                if (len > max_len)
3133                        max_len = len;
3134        }
3135}
3136
3137static void remove_file(struct patch *patch, int rmdir_empty)
3138{
3139        if (update_index) {
3140                if (remove_file_from_cache(patch->old_name) < 0)
3141                        die("unable to remove %s from index", patch->old_name);
3142        }
3143        if (!cached) {
3144                if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3145                        remove_path(patch->old_name);
3146                }
3147        }
3148}
3149
3150static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3151{
3152        struct stat st;
3153        struct cache_entry *ce;
3154        int namelen = strlen(path);
3155        unsigned ce_size = cache_entry_size(namelen);
3156
3157        if (!update_index)
3158                return;
3159
3160        ce = xcalloc(1, ce_size);
3161        memcpy(ce->name, path, namelen);
3162        ce->ce_mode = create_ce_mode(mode);
3163        ce->ce_flags = namelen;
3164        if (S_ISGITLINK(mode)) {
3165                const char *s = buf;
3166
3167                if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3168                        die("corrupt patch for subproject %s", path);
3169        } else {
3170                if (!cached) {
3171                        if (lstat(path, &st) < 0)
3172                                die_errno("unable to stat newly created file '%s'",
3173                                          path);
3174                        fill_stat_cache_info(ce, &st);
3175                }
3176                if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3177                        die("unable to create backing store for newly created file %s", path);
3178        }
3179        if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3180                die("unable to add cache entry for %s", path);
3181}
3182
3183static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3184{
3185        int fd;
3186        struct strbuf nbuf = STRBUF_INIT;
3187
3188        if (S_ISGITLINK(mode)) {
3189                struct stat st;
3190                if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3191                        return 0;
3192                return mkdir(path, 0777);
3193        }
3194
3195        if (has_symlinks && S_ISLNK(mode))
3196                /* Although buf:size is counted string, it also is NUL
3197                 * terminated.
3198                 */
3199                return symlink(buf, path);
3200
3201        fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3202        if (fd < 0)
3203                return -1;
3204
3205        if (convert_to_working_tree(path, buf, size, &nbuf)) {
3206                size = nbuf.len;
3207                buf  = nbuf.buf;
3208        }
3209        write_or_die(fd, buf, size);
3210        strbuf_release(&nbuf);
3211
3212        if (close(fd) < 0)
3213                die_errno("closing file '%s'", path);
3214        return 0;
3215}
3216
3217/*
3218 * We optimistically assume that the directories exist,
3219 * which is true 99% of the time anyway. If they don't,
3220 * we create them and try again.
3221 */
3222static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3223{
3224        if (cached)
3225                return;
3226        if (!try_create_file(path, mode, buf, size))
3227                return;
3228
3229        if (errno == ENOENT) {
3230                if (safe_create_leading_directories(path))
3231                        return;
3232                if (!try_create_file(path, mode, buf, size))
3233                        return;
3234        }
3235
3236        if (errno == EEXIST || errno == EACCES) {
3237                /* We may be trying to create a file where a directory
3238                 * used to be.
3239                 */
3240                struct stat st;
3241                if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3242                        errno = EEXIST;
3243        }
3244
3245        if (errno == EEXIST) {
3246                unsigned int nr = getpid();
3247
3248                for (;;) {
3249                        char newpath[PATH_MAX];
3250                        mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3251                        if (!try_create_file(newpath, mode, buf, size)) {
3252                                if (!rename(newpath, path))
3253                                        return;
3254                                unlink_or_warn(newpath);
3255                                break;
3256                        }
3257                        if (errno != EEXIST)
3258                                break;
3259                        ++nr;
3260                }
3261        }
3262        die_errno("unable to write file '%s' mode %o", path, mode);
3263}
3264
3265static void create_file(struct patch *patch)
3266{
3267        char *path = patch->new_name;
3268        unsigned mode = patch->new_mode;
3269        unsigned long size = patch->resultsize;
3270        char *buf = patch->result;
3271
3272        if (!mode)
3273                mode = S_IFREG | 0644;
3274        create_one_file(path, mode, buf, size);
3275        add_index_file(path, mode, buf, size);
3276}
3277
3278/* phase zero is to remove, phase one is to create */
3279static void write_out_one_result(struct patch *patch, int phase)
3280{
3281        if (patch->is_delete > 0) {
3282                if (phase == 0)
3283                        remove_file(patch, 1);
3284                return;
3285        }
3286        if (patch->is_new > 0 || patch->is_copy) {
3287                if (phase == 1)
3288                        create_file(patch);
3289                return;
3290        }
3291        /*
3292         * Rename or modification boils down to the same
3293         * thing: remove the old, write the new
3294         */
3295        if (phase == 0)
3296                remove_file(patch, patch->is_rename);
3297        if (phase == 1)
3298                create_file(patch);
3299}
3300
3301static int write_out_one_reject(struct patch *patch)
3302{
3303        FILE *rej;
3304        char namebuf[PATH_MAX];
3305        struct fragment *frag;
3306        int cnt = 0;
3307
3308        for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
3309                if (!frag->rejected)
3310                        continue;
3311                cnt++;
3312        }
3313
3314        if (!cnt) {
3315                if (apply_verbosely)
3316                        say_patch_name(stderr,
3317                                       "Applied patch ", patch, " cleanly.\n");
3318                return 0;
3319        }
3320
3321        /* This should not happen, because a removal patch that leaves
3322         * contents are marked "rejected" at the patch level.
3323         */
3324        if (!patch->new_name)
3325                die("internal error");
3326
3327        /* Say this even without --verbose */
3328        say_patch_name(stderr, "Applying patch ", patch, " with");
3329        fprintf(stderr, " %d rejects...\n", cnt);
3330
3331        cnt = strlen(patch->new_name);
3332        if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3333                cnt = ARRAY_SIZE(namebuf) - 5;
3334                warning("truncating .rej filename to %.*s.rej",
3335                        cnt - 1, patch->new_name);
3336        }
3337        memcpy(namebuf, patch->new_name, cnt);
3338        memcpy(namebuf + cnt, ".rej", 5);
3339
3340        rej = fopen(namebuf, "w");
3341        if (!rej)
3342                return error("cannot open %s: %s", namebuf, strerror(errno));
3343
3344        /* Normal git tools never deal with .rej, so do not pretend
3345         * this is a git patch by saying --git nor give extended
3346         * headers.  While at it, maybe please "kompare" that wants
3347         * the trailing TAB and some garbage at the end of line ;-).
3348         */
3349        fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3350                patch->new_name, patch->new_name);
3351        for (cnt = 1, frag = patch->fragments;
3352             frag;
3353             cnt++, frag = frag->next) {
3354                if (!frag->rejected) {
3355                        fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
3356                        continue;
3357                }
3358                fprintf(stderr, "Rejected hunk #%d.\n", cnt);
3359                fprintf(rej, "%.*s", frag->size, frag->patch);
3360                if (frag->patch[frag->size-1] != '\n')
3361                        fputc('\n', rej);
3362        }
3363        fclose(rej);
3364        return -1;
3365}
3366
3367static int write_out_results(struct patch *list, int skipped_patch)
3368{
3369        int phase;
3370        int errs = 0;
3371        struct patch *l;
3372
3373        if (!list && !skipped_patch)
3374                return error("No changes");
3375
3376        for (phase = 0; phase < 2; phase++) {
3377                l = list;
3378                while (l) {
3379                        if (l->rejected)
3380                                errs = 1;
3381                        else {
3382                                write_out_one_result(l, phase);
3383                                if (phase == 1 && write_out_one_reject(l))
3384                                        errs = 1;
3385                        }
3386                        l = l->next;
3387                }
3388        }
3389        return errs;
3390}
3391
3392static struct lock_file lock_file;
3393
3394static struct string_list limit_by_name;
3395static int has_include;
3396static void add_name_limit(const char *name, int exclude)
3397{
3398        struct string_list_item *it;
3399
3400        it = string_list_append(name, &limit_by_name);
3401        it->util = exclude ? NULL : (void *) 1;
3402}
3403
3404static int use_patch(struct patch *p)
3405{
3406        const char *pathname = p->new_name ? p->new_name : p->old_name;
3407        int i;
3408
3409        /* Paths outside are not touched regardless of "--include" */
3410        if (0 < prefix_length) {
3411                int pathlen = strlen(pathname);
3412                if (pathlen <= prefix_length ||
3413                    memcmp(prefix, pathname, prefix_length))
3414                        return 0;
3415        }
3416
3417        /* See if it matches any of exclude/include rule */
3418        for (i = 0; i < limit_by_name.nr; i++) {
3419                struct string_list_item *it = &limit_by_name.items[i];
3420                if (!fnmatch(it->string, pathname, 0))
3421                        return (it->util != NULL);
3422        }
3423
3424        /*
3425         * If we had any include, a path that does not match any rule is
3426         * not used.  Otherwise, we saw bunch of exclude rules (or none)
3427         * and such a path is used.
3428         */
3429        return !has_include;
3430}
3431
3432
3433static void prefix_one(char **name)
3434{
3435        char *old_name = *name;
3436        if (!old_name)
3437                return;
3438        *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3439        free(old_name);
3440}
3441
3442static void prefix_patches(struct patch *p)
3443{
3444        if (!prefix || p->is_toplevel_relative)
3445                return;
3446        for ( ; p; p = p->next) {
3447                if (p->new_name == p->old_name) {
3448                        char *prefixed = p->new_name;
3449                        prefix_one(&prefixed);
3450                        p->new_name = p->old_name = prefixed;
3451                }
3452                else {
3453                        prefix_one(&p->new_name);
3454                        prefix_one(&p->old_name);
3455                }
3456        }
3457}
3458
3459#define INACCURATE_EOF  (1<<0)
3460#define RECOUNT         (1<<1)
3461
3462static int apply_patch(int fd, const char *filename, int options)
3463{
3464        size_t offset;
3465        struct strbuf buf = STRBUF_INIT;
3466        struct patch *list = NULL, **listp = &list;
3467        int skipped_patch = 0;
3468
3469        /* FIXME - memory leak when using multiple patch files as inputs */
3470        memset(&fn_table, 0, sizeof(struct string_list));
3471        patch_input_file = filename;
3472        read_patch_file(&buf, fd);
3473        offset = 0;
3474        while (offset < buf.len) {
3475                struct patch *patch;
3476                int nr;
3477
3478                patch = xcalloc(1, sizeof(*patch));
3479                patch->inaccurate_eof = !!(options & INACCURATE_EOF);
3480                patch->recount =  !!(options & RECOUNT);
3481                nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
3482                if (nr < 0)
3483                        break;
3484                if (apply_in_reverse)
3485                        reverse_patches(patch);
3486                if (prefix)
3487                        prefix_patches(patch);
3488                if (use_patch(patch)) {
3489                        patch_stats(patch);
3490                        *listp = patch;
3491                        listp = &patch->next;
3492                }
3493                else {
3494                        /* perhaps free it a bit better? */
3495                        free(patch);
3496                        skipped_patch++;
3497                }
3498                offset += nr;
3499        }
3500
3501        if (whitespace_error && (ws_error_action == die_on_ws_error))
3502                apply = 0;
3503
3504        update_index = check_index && apply;
3505        if (update_index && newfd < 0)
3506                newfd = hold_locked_index(&lock_file, 1);
3507
3508        if (check_index) {
3509                if (read_cache() < 0)
3510                        die("unable to read index file");
3511        }
3512
3513        if ((check || apply) &&
3514            check_patch_list(list) < 0 &&
3515            !apply_with_reject)
3516                exit(1);
3517
3518        if (apply && write_out_results(list, skipped_patch))
3519                exit(1);
3520
3521        if (fake_ancestor)
3522                build_fake_ancestor(list, fake_ancestor);
3523
3524        if (diffstat)
3525                stat_patch_list(list);
3526
3527        if (numstat)
3528                numstat_patch_list(list);
3529
3530        if (summary)
3531                summary_patch_list(list);
3532
3533        strbuf_release(&buf);
3534        return 0;
3535}
3536
3537static int git_apply_config(const char *var, const char *value, void *cb)
3538{
3539        if (!strcmp(var, "apply.whitespace"))
3540                return git_config_string(&apply_default_whitespace, var, value);
3541        else if (!strcmp(var, "apply.ignorewhitespace"))
3542                return git_config_string(&apply_default_ignorewhitespace, var, value);
3543        return git_default_config(var, value, cb);
3544}
3545
3546static int option_parse_exclude(const struct option *opt,
3547                                const char *arg, int unset)
3548{
3549        add_name_limit(arg, 1);
3550        return 0;
3551}
3552
3553static int option_parse_include(const struct option *opt,
3554                                const char *arg, int unset)
3555{
3556        add_name_limit(arg, 0);
3557        has_include = 1;
3558        return 0;
3559}
3560
3561static int option_parse_p(const struct option *opt,
3562                          const char *arg, int unset)
3563{
3564        p_value = atoi(arg);
3565        p_value_known = 1;
3566        return 0;
3567}
3568
3569static int option_parse_z(const struct option *opt,
3570                          const char *arg, int unset)
3571{
3572        if (unset)
3573                line_termination = '\n';
3574        else
3575                line_termination = 0;
3576        return 0;
3577}
3578
3579static int option_parse_space_change(const struct option *opt,
3580                          const char *arg, int unset)
3581{
3582        if (unset)
3583                ws_ignore_action = ignore_ws_none;
3584        else
3585                ws_ignore_action = ignore_ws_change;
3586        return 0;
3587}
3588
3589static int option_parse_whitespace(const struct option *opt,
3590                                   const char *arg, int unset)
3591{
3592        const char **whitespace_option = opt->value;
3593
3594        *whitespace_option = arg;
3595        parse_whitespace_option(arg);
3596        return 0;
3597}
3598
3599static int option_parse_directory(const struct option *opt,
3600                                  const char *arg, int unset)
3601{
3602        root_len = strlen(arg);
3603        if (root_len && arg[root_len - 1] != '/') {
3604                char *new_root;
3605                root = new_root = xmalloc(root_len + 2);
3606                strcpy(new_root, arg);
3607                strcpy(new_root + root_len++, "/");
3608        } else
3609                root = arg;
3610        return 0;
3611}
3612
3613int cmd_apply(int argc, const char **argv, const char *unused_prefix)
3614{
3615        int i;
3616        int errs = 0;
3617        int is_not_gitdir;
3618        int binary;
3619        int force_apply = 0;
3620
3621        const char *whitespace_option = NULL;
3622
3623        struct option builtin_apply_options[] = {
3624                { OPTION_CALLBACK, 0, "exclude", NULL, "path",
3625                        "don't apply changes matching the given path",
3626                        0, option_parse_exclude },
3627                { OPTION_CALLBACK, 0, "include", NULL, "path",
3628                        "apply changes matching the given path",
3629                        0, option_parse_include },
3630                { OPTION_CALLBACK, 'p', NULL, NULL, "num",
3631                        "remove <num> leading slashes from traditional diff paths",
3632                        0, option_parse_p },
3633                OPT_BOOLEAN(0, "no-add", &no_add,
3634                        "ignore additions made by the patch"),
3635                OPT_BOOLEAN(0, "stat", &diffstat,
3636                        "instead of applying the patch, output diffstat for the input"),
3637                { OPTION_BOOLEAN, 0, "allow-binary-replacement", &binary,
3638                  NULL, "old option, now no-op",
3639                  PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },
3640                { OPTION_BOOLEAN, 0, "binary", &binary,
3641                  NULL, "old option, now no-op",
3642                  PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },
3643                OPT_BOOLEAN(0, "numstat", &numstat,
3644                        "shows number of added and deleted lines in decimal notation"),
3645                OPT_BOOLEAN(0, "summary", &summary,
3646                        "instead of applying the patch, output a summary for the input"),
3647                OPT_BOOLEAN(0, "check", &check,
3648                        "instead of applying the patch, see if the patch is applicable"),
3649                OPT_BOOLEAN(0, "index", &check_index,
3650                        "make sure the patch is applicable to the current index"),
3651                OPT_BOOLEAN(0, "cached", &cached,
3652                        "apply a patch without touching the working tree"),
3653                OPT_BOOLEAN(0, "apply", &force_apply,
3654                        "also apply the patch (use with --stat/--summary/--check)"),
3655                OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
3656                        "build a temporary index based on embedded index information"),
3657                { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
3658                        "paths are separated with NUL character",
3659                        PARSE_OPT_NOARG, option_parse_z },
3660                OPT_INTEGER('C', NULL, &p_context,
3661                                "ensure at least <n> lines of context match"),
3662                { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, "action",
3663                        "detect new or modified lines that have whitespace errors",
3664                        0, option_parse_whitespace },
3665                { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
3666                        "ignore changes in whitespace when finding context",
3667                        PARSE_OPT_NOARG, option_parse_space_change },
3668                { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
3669                        "ignore changes in whitespace when finding context",
3670                        PARSE_OPT_NOARG, option_parse_space_change },
3671                OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
3672                        "apply the patch in reverse"),
3673                OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
3674                        "don't expect at least one line of context"),
3675                OPT_BOOLEAN(0, "reject", &apply_with_reject,
3676                        "leave the rejected hunks in corresponding *.rej files"),
3677                OPT__VERBOSE(&apply_verbosely),
3678                OPT_BIT(0, "inaccurate-eof", &options,
3679                        "tolerate incorrectly detected missing new-line at the end of file",
3680                        INACCURATE_EOF),
3681                OPT_BIT(0, "recount", &options,
3682                        "do not trust the line counts in the hunk headers",
3683                        RECOUNT),
3684                { OPTION_CALLBACK, 0, "directory", NULL, "root",
3685                        "prepend <root> to all filenames",
3686                        0, option_parse_directory },
3687                OPT_END()
3688        };
3689
3690        prefix = setup_git_directory_gently(&is_not_gitdir);
3691        prefix_length = prefix ? strlen(prefix) : 0;
3692        git_config(git_apply_config, NULL);
3693        if (apply_default_whitespace)
3694                parse_whitespace_option(apply_default_whitespace);
3695        if (apply_default_ignorewhitespace)
3696                parse_ignorewhitespace_option(apply_default_ignorewhitespace);
3697
3698        argc = parse_options(argc, argv, prefix, builtin_apply_options,
3699                        apply_usage, 0);
3700
3701        if (apply_with_reject)
3702                apply = apply_verbosely = 1;
3703        if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
3704                apply = 0;
3705        if (check_index && is_not_gitdir)
3706                die("--index outside a repository");
3707        if (cached) {
3708                if (is_not_gitdir)
3709                        die("--cached outside a repository");
3710                check_index = 1;
3711        }
3712        for (i = 0; i < argc; i++) {
3713                const char *arg = argv[i];
3714                int fd;
3715
3716                if (!strcmp(arg, "-")) {
3717                        errs |= apply_patch(0, "<stdin>", options);
3718                        read_stdin = 0;
3719                        continue;
3720                } else if (0 < prefix_length)
3721                        arg = prefix_filename(prefix, prefix_length, arg);
3722
3723                fd = open(arg, O_RDONLY);
3724                if (fd < 0)
3725                        die_errno("can't open patch '%s'", arg);
3726                read_stdin = 0;
3727                set_default_whitespace_mode(whitespace_option);
3728                errs |= apply_patch(fd, arg, options);
3729                close(fd);
3730        }
3731        set_default_whitespace_mode(whitespace_option);
3732        if (read_stdin)
3733                errs |= apply_patch(0, "<stdin>", options);
3734        if (whitespace_error) {
3735                if (squelch_whitespace_errors &&
3736                    squelch_whitespace_errors < whitespace_error) {
3737                        int squelched =
3738                                whitespace_error - squelch_whitespace_errors;
3739                        warning("squelched %d "
3740                                "whitespace error%s",
3741                                squelched,
3742                                squelched == 1 ? "" : "s");
3743                }
3744                if (ws_error_action == die_on_ws_error)
3745                        die("%d line%s add%s whitespace errors.",
3746                            whitespace_error,
3747                            whitespace_error == 1 ? "" : "s",
3748                            whitespace_error == 1 ? "s" : "");
3749                if (applied_after_fixing_ws && apply)
3750                        warning("%d line%s applied after"
3751                                " fixing whitespace errors.",
3752                                applied_after_fixing_ws,
3753                                applied_after_fixing_ws == 1 ? "" : "s");
3754                else if (whitespace_error)
3755                        warning("%d line%s add%s whitespace errors.",
3756                                whitespace_error,
3757                                whitespace_error == 1 ? "" : "s",
3758                                whitespace_error == 1 ? "s" : "");
3759        }
3760
3761        if (update_index) {
3762                if (write_cache(newfd, active_cache, active_nr) ||
3763                    commit_locked_index(&lock_file))
3764                        die("Unable to write new index file");
3765        }
3766
3767        return !!errs;
3768}