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