builtin-apply.con commit apply: check D/F conflicts more carefully. (c28c571)
   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 <fnmatch.h>
  10#include "cache.h"
  11#include "cache-tree.h"
  12#include "quote.h"
  13#include "blob.h"
  14#include "delta.h"
  15#include "builtin.h"
  16
  17/*
  18 *  --check turns on checking that the working tree matches the
  19 *    files that are being modified, but doesn't apply the patch
  20 *  --stat does just a diffstat, and doesn't actually apply
  21 *  --numstat does numeric diffstat, and doesn't actually apply
  22 *  --index-info shows the old and new index info for paths if available.
  23 *  --index updates the cache as well.
  24 *  --cached updates only the cache without ever touching the working tree.
  25 */
  26static const char *prefix;
  27static int prefix_length = -1;
  28static int newfd = -1;
  29
  30static int p_value = 1;
  31static int allow_binary_replacement = 0;
  32static int check_index = 0;
  33static int write_index = 0;
  34static int cached = 0;
  35static int diffstat = 0;
  36static int numstat = 0;
  37static int summary = 0;
  38static int check = 0;
  39static int apply = 1;
  40static int no_add = 0;
  41static int show_index_info = 0;
  42static int line_termination = '\n';
  43static unsigned long p_context = -1;
  44static const char apply_usage[] =
  45"git-apply [--stat] [--numstat] [--summary] [--check] [--index] [--cached] [--apply] [--no-add] [--index-info] [--allow-binary-replacement] [-z] [-pNUM] [-CNUM] [--whitespace=<nowarn|warn|error|error-all|strip>] <patch>...";
  46
  47static enum whitespace_eol {
  48        nowarn_whitespace,
  49        warn_on_whitespace,
  50        error_on_whitespace,
  51        strip_whitespace,
  52} new_whitespace = warn_on_whitespace;
  53static int whitespace_error = 0;
  54static int squelch_whitespace_errors = 5;
  55static int applied_after_stripping = 0;
  56static const char *patch_input_file = NULL;
  57
  58static void parse_whitespace_option(const char *option)
  59{
  60        if (!option) {
  61                new_whitespace = warn_on_whitespace;
  62                return;
  63        }
  64        if (!strcmp(option, "warn")) {
  65                new_whitespace = warn_on_whitespace;
  66                return;
  67        }
  68        if (!strcmp(option, "nowarn")) {
  69                new_whitespace = nowarn_whitespace;
  70                return;
  71        }
  72        if (!strcmp(option, "error")) {
  73                new_whitespace = error_on_whitespace;
  74                return;
  75        }
  76        if (!strcmp(option, "error-all")) {
  77                new_whitespace = error_on_whitespace;
  78                squelch_whitespace_errors = 0;
  79                return;
  80        }
  81        if (!strcmp(option, "strip")) {
  82                new_whitespace = strip_whitespace;
  83                return;
  84        }
  85        die("unrecognized whitespace option '%s'", option);
  86}
  87
  88static void set_default_whitespace_mode(const char *whitespace_option)
  89{
  90        if (!whitespace_option && !apply_default_whitespace) {
  91                new_whitespace = (apply
  92                                  ? warn_on_whitespace
  93                                  : nowarn_whitespace);
  94        }
  95}
  96
  97/*
  98 * For "diff-stat" like behaviour, we keep track of the biggest change
  99 * we've seen, and the longest filename. That allows us to do simple
 100 * scaling.
 101 */
 102static int max_change, max_len;
 103
 104/*
 105 * Various "current state", notably line numbers and what
 106 * file (and how) we're patching right now.. The "is_xxxx"
 107 * things are flags, where -1 means "don't know yet".
 108 */
 109static int linenr = 1;
 110
 111struct fragment {
 112        unsigned long leading, trailing;
 113        unsigned long oldpos, oldlines;
 114        unsigned long newpos, newlines;
 115        const char *patch;
 116        int size;
 117        struct fragment *next;
 118};
 119
 120struct patch {
 121        char *new_name, *old_name, *def_name;
 122        unsigned int old_mode, new_mode;
 123        int is_rename, is_copy, is_new, is_delete, is_binary;
 124#define BINARY_DELTA_DEFLATED 1
 125#define BINARY_LITERAL_DEFLATED 2
 126        unsigned long deflate_origlen;
 127        int lines_added, lines_deleted;
 128        int score;
 129        int inaccurate_eof:1;
 130        struct fragment *fragments;
 131        char *result;
 132        unsigned long resultsize;
 133        char old_sha1_prefix[41];
 134        char new_sha1_prefix[41];
 135        struct patch *next;
 136};
 137
 138#define CHUNKSIZE (8192)
 139#define SLOP (16)
 140
 141static void *read_patch_file(int fd, unsigned long *sizep)
 142{
 143        unsigned long size = 0, alloc = CHUNKSIZE;
 144        void *buffer = xmalloc(alloc);
 145
 146        for (;;) {
 147                int nr = alloc - size;
 148                if (nr < 1024) {
 149                        alloc += CHUNKSIZE;
 150                        buffer = xrealloc(buffer, alloc);
 151                        nr = alloc - size;
 152                }
 153                nr = xread(fd, (char *) buffer + size, nr);
 154                if (!nr)
 155                        break;
 156                if (nr < 0)
 157                        die("git-apply: read returned %s", strerror(errno));
 158                size += nr;
 159        }
 160        *sizep = size;
 161
 162        /*
 163         * Make sure that we have some slop in the buffer
 164         * so that we can do speculative "memcmp" etc, and
 165         * see to it that it is NUL-filled.
 166         */
 167        if (alloc < size + SLOP)
 168                buffer = xrealloc(buffer, size + SLOP);
 169        memset((char *) buffer + size, 0, SLOP);
 170        return buffer;
 171}
 172
 173static unsigned long linelen(const char *buffer, unsigned long size)
 174{
 175        unsigned long len = 0;
 176        while (size--) {
 177                len++;
 178                if (*buffer++ == '\n')
 179                        break;
 180        }
 181        return len;
 182}
 183
 184static int is_dev_null(const char *str)
 185{
 186        return !memcmp("/dev/null", str, 9) && isspace(str[9]);
 187}
 188
 189#define TERM_SPACE      1
 190#define TERM_TAB        2
 191
 192static int name_terminate(const char *name, int namelen, int c, int terminate)
 193{
 194        if (c == ' ' && !(terminate & TERM_SPACE))
 195                return 0;
 196        if (c == '\t' && !(terminate & TERM_TAB))
 197                return 0;
 198
 199        return 1;
 200}
 201
 202static char * find_name(const char *line, char *def, int p_value, int terminate)
 203{
 204        int len;
 205        const char *start = line;
 206        char *name;
 207
 208        if (*line == '"') {
 209                /* Proposed "new-style" GNU patch/diff format; see
 210                 * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
 211                 */
 212                name = unquote_c_style(line, NULL);
 213                if (name) {
 214                        char *cp = name;
 215                        while (p_value) {
 216                                cp = strchr(name, '/');
 217                                if (!cp)
 218                                        break;
 219                                cp++;
 220                                p_value--;
 221                        }
 222                        if (cp) {
 223                                /* name can later be freed, so we need
 224                                 * to memmove, not just return cp
 225                                 */
 226                                memmove(name, cp, strlen(cp) + 1);
 227                                free(def);
 228                                return name;
 229                        }
 230                        else {
 231                                free(name);
 232                                name = NULL;
 233                        }
 234                }
 235        }
 236
 237        for (;;) {
 238                char c = *line;
 239
 240                if (isspace(c)) {
 241                        if (c == '\n')
 242                                break;
 243                        if (name_terminate(start, line-start, c, terminate))
 244                                break;
 245                }
 246                line++;
 247                if (c == '/' && !--p_value)
 248                        start = line;
 249        }
 250        if (!start)
 251                return def;
 252        len = line - start;
 253        if (!len)
 254                return def;
 255
 256        /*
 257         * Generally we prefer the shorter name, especially
 258         * if the other one is just a variation of that with
 259         * something else tacked on to the end (ie "file.orig"
 260         * or "file~").
 261         */
 262        if (def) {
 263                int deflen = strlen(def);
 264                if (deflen < len && !strncmp(start, def, deflen))
 265                        return def;
 266        }
 267
 268        name = xmalloc(len + 1);
 269        memcpy(name, start, len);
 270        name[len] = 0;
 271        free(def);
 272        return name;
 273}
 274
 275/*
 276 * Get the name etc info from the --/+++ lines of a traditional patch header
 277 *
 278 * NOTE! This hardcodes "-p1" behaviour in filename detection.
 279 *
 280 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
 281 * files, we can happily check the index for a match, but for creating a
 282 * new file we should try to match whatever "patch" does. I have no idea.
 283 */
 284static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
 285{
 286        char *name;
 287
 288        first += 4;     /* skip "--- " */
 289        second += 4;    /* skip "+++ " */
 290        if (is_dev_null(first)) {
 291                patch->is_new = 1;
 292                patch->is_delete = 0;
 293                name = find_name(second, NULL, p_value, TERM_SPACE | TERM_TAB);
 294                patch->new_name = name;
 295        } else if (is_dev_null(second)) {
 296                patch->is_new = 0;
 297                patch->is_delete = 1;
 298                name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
 299                patch->old_name = name;
 300        } else {
 301                name = find_name(first, NULL, p_value, TERM_SPACE | TERM_TAB);
 302                name = find_name(second, name, p_value, TERM_SPACE | TERM_TAB);
 303                patch->old_name = patch->new_name = name;
 304        }
 305        if (!name)
 306                die("unable to find filename in patch at line %d", linenr);
 307}
 308
 309static int gitdiff_hdrend(const char *line, struct patch *patch)
 310{
 311        return -1;
 312}
 313
 314/*
 315 * We're anal about diff header consistency, to make
 316 * sure that we don't end up having strange ambiguous
 317 * patches floating around.
 318 *
 319 * As a result, gitdiff_{old|new}name() will check
 320 * their names against any previous information, just
 321 * to make sure..
 322 */
 323static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
 324{
 325        if (!orig_name && !isnull)
 326                return find_name(line, NULL, 1, 0);
 327
 328        if (orig_name) {
 329                int len;
 330                const char *name;
 331                char *another;
 332                name = orig_name;
 333                len = strlen(name);
 334                if (isnull)
 335                        die("git-apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
 336                another = find_name(line, NULL, 1, 0);
 337                if (!another || memcmp(another, name, len))
 338                        die("git-apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
 339                free(another);
 340                return orig_name;
 341        }
 342        else {
 343                /* expect "/dev/null" */
 344                if (memcmp("/dev/null", line, 9) || line[9] != '\n')
 345                        die("git-apply: bad git-diff - expected /dev/null on line %d", linenr);
 346                return NULL;
 347        }
 348}
 349
 350static int gitdiff_oldname(const char *line, struct patch *patch)
 351{
 352        patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
 353        return 0;
 354}
 355
 356static int gitdiff_newname(const char *line, struct patch *patch)
 357{
 358        patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
 359        return 0;
 360}
 361
 362static int gitdiff_oldmode(const char *line, struct patch *patch)
 363{
 364        patch->old_mode = strtoul(line, NULL, 8);
 365        return 0;
 366}
 367
 368static int gitdiff_newmode(const char *line, struct patch *patch)
 369{
 370        patch->new_mode = strtoul(line, NULL, 8);
 371        return 0;
 372}
 373
 374static int gitdiff_delete(const char *line, struct patch *patch)
 375{
 376        patch->is_delete = 1;
 377        patch->old_name = patch->def_name;
 378        return gitdiff_oldmode(line, patch);
 379}
 380
 381static int gitdiff_newfile(const char *line, struct patch *patch)
 382{
 383        patch->is_new = 1;
 384        patch->new_name = patch->def_name;
 385        return gitdiff_newmode(line, patch);
 386}
 387
 388static int gitdiff_copysrc(const char *line, struct patch *patch)
 389{
 390        patch->is_copy = 1;
 391        patch->old_name = find_name(line, NULL, 0, 0);
 392        return 0;
 393}
 394
 395static int gitdiff_copydst(const char *line, struct patch *patch)
 396{
 397        patch->is_copy = 1;
 398        patch->new_name = find_name(line, NULL, 0, 0);
 399        return 0;
 400}
 401
 402static int gitdiff_renamesrc(const char *line, struct patch *patch)
 403{
 404        patch->is_rename = 1;
 405        patch->old_name = find_name(line, NULL, 0, 0);
 406        return 0;
 407}
 408
 409static int gitdiff_renamedst(const char *line, struct patch *patch)
 410{
 411        patch->is_rename = 1;
 412        patch->new_name = find_name(line, NULL, 0, 0);
 413        return 0;
 414}
 415
 416static int gitdiff_similarity(const char *line, struct patch *patch)
 417{
 418        if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
 419                patch->score = 0;
 420        return 0;
 421}
 422
 423static int gitdiff_dissimilarity(const char *line, struct patch *patch)
 424{
 425        if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
 426                patch->score = 0;
 427        return 0;
 428}
 429
 430static int gitdiff_index(const char *line, struct patch *patch)
 431{
 432        /* index line is N hexadecimal, "..", N hexadecimal,
 433         * and optional space with octal mode.
 434         */
 435        const char *ptr, *eol;
 436        int len;
 437
 438        ptr = strchr(line, '.');
 439        if (!ptr || ptr[1] != '.' || 40 < ptr - line)
 440                return 0;
 441        len = ptr - line;
 442        memcpy(patch->old_sha1_prefix, line, len);
 443        patch->old_sha1_prefix[len] = 0;
 444
 445        line = ptr + 2;
 446        ptr = strchr(line, ' ');
 447        eol = strchr(line, '\n');
 448
 449        if (!ptr || eol < ptr)
 450                ptr = eol;
 451        len = ptr - line;
 452
 453        if (40 < len)
 454                return 0;
 455        memcpy(patch->new_sha1_prefix, line, len);
 456        patch->new_sha1_prefix[len] = 0;
 457        if (*ptr == ' ')
 458                patch->new_mode = patch->old_mode = strtoul(ptr+1, NULL, 8);
 459        return 0;
 460}
 461
 462/*
 463 * This is normal for a diff that doesn't change anything: we'll fall through
 464 * into the next diff. Tell the parser to break out.
 465 */
 466static int gitdiff_unrecognized(const char *line, struct patch *patch)
 467{
 468        return -1;
 469}
 470
 471static const char *stop_at_slash(const char *line, int llen)
 472{
 473        int i;
 474
 475        for (i = 0; i < llen; i++) {
 476                int ch = line[i];
 477                if (ch == '/')
 478                        return line + i;
 479        }
 480        return NULL;
 481}
 482
 483/* This is to extract the same name that appears on "diff --git"
 484 * line.  We do not find and return anything if it is a rename
 485 * patch, and it is OK because we will find the name elsewhere.
 486 * We need to reliably find name only when it is mode-change only,
 487 * creation or deletion of an empty file.  In any of these cases,
 488 * both sides are the same name under a/ and b/ respectively.
 489 */
 490static char *git_header_name(char *line, int llen)
 491{
 492        int len;
 493        const char *name;
 494        const char *second = NULL;
 495
 496        line += strlen("diff --git ");
 497        llen -= strlen("diff --git ");
 498
 499        if (*line == '"') {
 500                const char *cp;
 501                char *first = unquote_c_style(line, &second);
 502                if (!first)
 503                        return NULL;
 504
 505                /* advance to the first slash */
 506                cp = stop_at_slash(first, strlen(first));
 507                if (!cp || cp == first) {
 508                        /* we do not accept absolute paths */
 509                free_first_and_fail:
 510                        free(first);
 511                        return NULL;
 512                }
 513                len = strlen(cp+1);
 514                memmove(first, cp+1, len+1); /* including NUL */
 515
 516                /* second points at one past closing dq of name.
 517                 * find the second name.
 518                 */
 519                while ((second < line + llen) && isspace(*second))
 520                        second++;
 521
 522                if (line + llen <= second)
 523                        goto free_first_and_fail;
 524                if (*second == '"') {
 525                        char *sp = unquote_c_style(second, NULL);
 526                        if (!sp)
 527                                goto free_first_and_fail;
 528                        cp = stop_at_slash(sp, strlen(sp));
 529                        if (!cp || cp == sp) {
 530                        free_both_and_fail:
 531                                free(sp);
 532                                goto free_first_and_fail;
 533                        }
 534                        /* They must match, otherwise ignore */
 535                        if (strcmp(cp+1, first))
 536                                goto free_both_and_fail;
 537                        free(sp);
 538                        return first;
 539                }
 540
 541                /* unquoted second */
 542                cp = stop_at_slash(second, line + llen - second);
 543                if (!cp || cp == second)
 544                        goto free_first_and_fail;
 545                cp++;
 546                if (line + llen - cp != len + 1 ||
 547                    memcmp(first, cp, len))
 548                        goto free_first_and_fail;
 549                return first;
 550        }
 551
 552        /* unquoted first name */
 553        name = stop_at_slash(line, llen);
 554        if (!name || name == line)
 555                return NULL;
 556
 557        name++;
 558
 559        /* since the first name is unquoted, a dq if exists must be
 560         * the beginning of the second name.
 561         */
 562        for (second = name; second < line + llen; second++) {
 563                if (*second == '"') {
 564                        const char *cp = second;
 565                        const char *np;
 566                        char *sp = unquote_c_style(second, NULL);
 567
 568                        if (!sp)
 569                                return NULL;
 570                        np = stop_at_slash(sp, strlen(sp));
 571                        if (!np || np == sp) {
 572                        free_second_and_fail:
 573                                free(sp);
 574                                return NULL;
 575                        }
 576                        np++;
 577                        len = strlen(np);
 578                        if (len < cp - name &&
 579                            !strncmp(np, name, len) &&
 580                            isspace(name[len])) {
 581                                /* Good */
 582                                memmove(sp, np, len + 1);
 583                                return sp;
 584                        }
 585                        goto free_second_and_fail;
 586                }
 587        }
 588
 589        /*
 590         * Accept a name only if it shows up twice, exactly the same
 591         * form.
 592         */
 593        for (len = 0 ; ; len++) {
 594                char c = name[len];
 595
 596                switch (c) {
 597                default:
 598                        continue;
 599                case '\n':
 600                        return NULL;
 601                case '\t': case ' ':
 602                        second = name+len;
 603                        for (;;) {
 604                                char c = *second++;
 605                                if (c == '\n')
 606                                        return NULL;
 607                                if (c == '/')
 608                                        break;
 609                        }
 610                        if (second[len] == '\n' && !memcmp(name, second, len)) {
 611                                char *ret = xmalloc(len + 1);
 612                                memcpy(ret, name, len);
 613                                ret[len] = 0;
 614                                return ret;
 615                        }
 616                }
 617        }
 618        return NULL;
 619}
 620
 621/* Verify that we recognize the lines following a git header */
 622static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
 623{
 624        unsigned long offset;
 625
 626        /* A git diff has explicit new/delete information, so we don't guess */
 627        patch->is_new = 0;
 628        patch->is_delete = 0;
 629
 630        /*
 631         * Some things may not have the old name in the
 632         * rest of the headers anywhere (pure mode changes,
 633         * or removing or adding empty files), so we get
 634         * the default name from the header.
 635         */
 636        patch->def_name = git_header_name(line, len);
 637
 638        line += len;
 639        size -= len;
 640        linenr++;
 641        for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
 642                static const struct opentry {
 643                        const char *str;
 644                        int (*fn)(const char *, struct patch *);
 645                } optable[] = {
 646                        { "@@ -", gitdiff_hdrend },
 647                        { "--- ", gitdiff_oldname },
 648                        { "+++ ", gitdiff_newname },
 649                        { "old mode ", gitdiff_oldmode },
 650                        { "new mode ", gitdiff_newmode },
 651                        { "deleted file mode ", gitdiff_delete },
 652                        { "new file mode ", gitdiff_newfile },
 653                        { "copy from ", gitdiff_copysrc },
 654                        { "copy to ", gitdiff_copydst },
 655                        { "rename old ", gitdiff_renamesrc },
 656                        { "rename new ", gitdiff_renamedst },
 657                        { "rename from ", gitdiff_renamesrc },
 658                        { "rename to ", gitdiff_renamedst },
 659                        { "similarity index ", gitdiff_similarity },
 660                        { "dissimilarity index ", gitdiff_dissimilarity },
 661                        { "index ", gitdiff_index },
 662                        { "", gitdiff_unrecognized },
 663                };
 664                int i;
 665
 666                len = linelen(line, size);
 667                if (!len || line[len-1] != '\n')
 668                        break;
 669                for (i = 0; i < ARRAY_SIZE(optable); i++) {
 670                        const struct opentry *p = optable + i;
 671                        int oplen = strlen(p->str);
 672                        if (len < oplen || memcmp(p->str, line, oplen))
 673                                continue;
 674                        if (p->fn(line + oplen, patch) < 0)
 675                                return offset;
 676                        break;
 677                }
 678        }
 679
 680        return offset;
 681}
 682
 683static int parse_num(const char *line, unsigned long *p)
 684{
 685        char *ptr;
 686
 687        if (!isdigit(*line))
 688                return 0;
 689        *p = strtoul(line, &ptr, 10);
 690        return ptr - line;
 691}
 692
 693static int parse_range(const char *line, int len, int offset, const char *expect,
 694                        unsigned long *p1, unsigned long *p2)
 695{
 696        int digits, ex;
 697
 698        if (offset < 0 || offset >= len)
 699                return -1;
 700        line += offset;
 701        len -= offset;
 702
 703        digits = parse_num(line, p1);
 704        if (!digits)
 705                return -1;
 706
 707        offset += digits;
 708        line += digits;
 709        len -= digits;
 710
 711        *p2 = 1;
 712        if (*line == ',') {
 713                digits = parse_num(line+1, p2);
 714                if (!digits)
 715                        return -1;
 716
 717                offset += digits+1;
 718                line += digits+1;
 719                len -= digits+1;
 720        }
 721
 722        ex = strlen(expect);
 723        if (ex > len)
 724                return -1;
 725        if (memcmp(line, expect, ex))
 726                return -1;
 727
 728        return offset + ex;
 729}
 730
 731/*
 732 * Parse a unified diff fragment header of the
 733 * form "@@ -a,b +c,d @@"
 734 */
 735static int parse_fragment_header(char *line, int len, struct fragment *fragment)
 736{
 737        int offset;
 738
 739        if (!len || line[len-1] != '\n')
 740                return -1;
 741
 742        /* Figure out the number of lines in a fragment */
 743        offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
 744        offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
 745
 746        return offset;
 747}
 748
 749static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
 750{
 751        unsigned long offset, len;
 752
 753        patch->is_rename = patch->is_copy = 0;
 754        patch->is_new = patch->is_delete = -1;
 755        patch->old_mode = patch->new_mode = 0;
 756        patch->old_name = patch->new_name = NULL;
 757        for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
 758                unsigned long nextlen;
 759
 760                len = linelen(line, size);
 761                if (!len)
 762                        break;
 763
 764                /* Testing this early allows us to take a few shortcuts.. */
 765                if (len < 6)
 766                        continue;
 767
 768                /*
 769                 * Make sure we don't find any unconnected patch fragments.
 770                 * That's a sign that we didn't find a header, and that a
 771                 * patch has become corrupted/broken up.
 772                 */
 773                if (!memcmp("@@ -", line, 4)) {
 774                        struct fragment dummy;
 775                        if (parse_fragment_header(line, len, &dummy) < 0)
 776                                continue;
 777                        error("patch fragment without header at line %d: %.*s", linenr, (int)len-1, line);
 778                }
 779
 780                if (size < len + 6)
 781                        break;
 782
 783                /*
 784                 * Git patch? It might not have a real patch, just a rename
 785                 * or mode change, so we handle that specially
 786                 */
 787                if (!memcmp("diff --git ", line, 11)) {
 788                        int git_hdr_len = parse_git_header(line, len, size, patch);
 789                        if (git_hdr_len <= len)
 790                                continue;
 791                        if (!patch->old_name && !patch->new_name) {
 792                                if (!patch->def_name)
 793                                        die("git diff header lacks filename information (line %d)", linenr);
 794                                patch->old_name = patch->new_name = patch->def_name;
 795                        }
 796                        *hdrsize = git_hdr_len;
 797                        return offset;
 798                }
 799
 800                /** --- followed by +++ ? */
 801                if (memcmp("--- ", line,  4) || memcmp("+++ ", line + len, 4))
 802                        continue;
 803
 804                /*
 805                 * We only accept unified patches, so we want it to
 806                 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
 807                 * minimum
 808                 */
 809                nextlen = linelen(line + len, size - len);
 810                if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
 811                        continue;
 812
 813                /* Ok, we'll consider it a patch */
 814                parse_traditional_patch(line, line+len, patch);
 815                *hdrsize = len + nextlen;
 816                linenr += 2;
 817                return offset;
 818        }
 819        return -1;
 820}
 821
 822/*
 823 * Parse a unified diff. Note that this really needs
 824 * to parse each fragment separately, since the only
 825 * way to know the difference between a "---" that is
 826 * part of a patch, and a "---" that starts the next
 827 * patch is to look at the line counts..
 828 */
 829static int parse_fragment(char *line, unsigned long size, struct patch *patch, struct fragment *fragment)
 830{
 831        int added, deleted;
 832        int len = linelen(line, size), offset;
 833        unsigned long oldlines, newlines;
 834        unsigned long leading, trailing;
 835
 836        offset = parse_fragment_header(line, len, fragment);
 837        if (offset < 0)
 838                return -1;
 839        oldlines = fragment->oldlines;
 840        newlines = fragment->newlines;
 841        leading = 0;
 842        trailing = 0;
 843
 844        if (patch->is_new < 0) {
 845                patch->is_new =  !oldlines;
 846                if (!oldlines)
 847                        patch->old_name = NULL;
 848        }
 849        if (patch->is_delete < 0) {
 850                patch->is_delete = !newlines;
 851                if (!newlines)
 852                        patch->new_name = NULL;
 853        }
 854
 855        if (patch->is_new && oldlines)
 856                return error("new file depends on old contents");
 857        if (patch->is_delete != !newlines) {
 858                if (newlines)
 859                        return error("deleted file still has contents");
 860                fprintf(stderr, "** warning: file %s becomes empty but is not deleted\n", patch->new_name);
 861        }
 862
 863        /* Parse the thing.. */
 864        line += len;
 865        size -= len;
 866        linenr++;
 867        added = deleted = 0;
 868        for (offset = len; size > 0; offset += len, size -= len, line += len, linenr++) {
 869                if (!oldlines && !newlines)
 870                        break;
 871                len = linelen(line, size);
 872                if (!len || line[len-1] != '\n')
 873                        return -1;
 874                switch (*line) {
 875                default:
 876                        return -1;
 877                case ' ':
 878                        oldlines--;
 879                        newlines--;
 880                        if (!deleted && !added)
 881                                leading++;
 882                        trailing++;
 883                        break;
 884                case '-':
 885                        deleted++;
 886                        oldlines--;
 887                        trailing = 0;
 888                        break;
 889                case '+':
 890                        /*
 891                         * We know len is at least two, since we have a '+' and
 892                         * we checked that the last character was a '\n' above.
 893                         * That is, an addition of an empty line would check
 894                         * the '+' here.  Sneaky...
 895                         */
 896                        if ((new_whitespace != nowarn_whitespace) &&
 897                            isspace(line[len-2])) {
 898                                whitespace_error++;
 899                                if (squelch_whitespace_errors &&
 900                                    squelch_whitespace_errors <
 901                                    whitespace_error)
 902                                        ;
 903                                else {
 904                                        fprintf(stderr, "Adds trailing whitespace.\n%s:%d:%.*s\n",
 905                                                patch_input_file,
 906                                                linenr, len-2, line+1);
 907                                }
 908                        }
 909                        added++;
 910                        newlines--;
 911                        trailing = 0;
 912                        break;
 913
 914                /* We allow "\ No newline at end of file". Depending
 915                 * on locale settings when the patch was produced we
 916                 * don't know what this line looks like. The only
 917                 * thing we do know is that it begins with "\ ".
 918                 * Checking for 12 is just for sanity check -- any
 919                 * l10n of "\ No newline..." is at least that long.
 920                 */
 921                case '\\':
 922                        if (len < 12 || memcmp(line, "\\ ", 2))
 923                                return -1;
 924                        break;
 925                }
 926        }
 927        if (oldlines || newlines)
 928                return -1;
 929        fragment->leading = leading;
 930        fragment->trailing = trailing;
 931
 932        /* If a fragment ends with an incomplete line, we failed to include
 933         * it in the above loop because we hit oldlines == newlines == 0
 934         * before seeing it.
 935         */
 936        if (12 < size && !memcmp(line, "\\ ", 2))
 937                offset += linelen(line, size);
 938
 939        patch->lines_added += added;
 940        patch->lines_deleted += deleted;
 941        return offset;
 942}
 943
 944static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
 945{
 946        unsigned long offset = 0;
 947        struct fragment **fragp = &patch->fragments;
 948
 949        while (size > 4 && !memcmp(line, "@@ -", 4)) {
 950                struct fragment *fragment;
 951                int len;
 952
 953                fragment = xcalloc(1, sizeof(*fragment));
 954                len = parse_fragment(line, size, patch, fragment);
 955                if (len <= 0)
 956                        die("corrupt patch at line %d", linenr);
 957
 958                fragment->patch = line;
 959                fragment->size = len;
 960
 961                *fragp = fragment;
 962                fragp = &fragment->next;
 963
 964                offset += len;
 965                line += len;
 966                size -= len;
 967        }
 968        return offset;
 969}
 970
 971static inline int metadata_changes(struct patch *patch)
 972{
 973        return  patch->is_rename > 0 ||
 974                patch->is_copy > 0 ||
 975                patch->is_new > 0 ||
 976                patch->is_delete ||
 977                (patch->old_mode && patch->new_mode &&
 978                 patch->old_mode != patch->new_mode);
 979}
 980
 981static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
 982{
 983        /* We have read "GIT binary patch\n"; what follows is a line
 984         * that says the patch method (currently, either "deflated
 985         * literal" or "deflated delta") and the length of data before
 986         * deflating; a sequence of 'length-byte' followed by base-85
 987         * encoded data follows.
 988         *
 989         * Each 5-byte sequence of base-85 encodes up to 4 bytes,
 990         * and we would limit the patch line to 66 characters,
 991         * so one line can fit up to 13 groups that would decode
 992         * to 52 bytes max.  The length byte 'A'-'Z' corresponds
 993         * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
 994         * The end of binary is signaled with an empty line.
 995         */
 996        int llen, used;
 997        struct fragment *fragment;
 998        char *data = NULL;
 999
1000        patch->fragments = fragment = xcalloc(1, sizeof(*fragment));
1001
1002        /* Grab the type of patch */
1003        llen = linelen(buffer, size);
1004        used = llen;
1005        linenr++;
1006
1007        if (!strncmp(buffer, "delta ", 6)) {
1008                patch->is_binary = BINARY_DELTA_DEFLATED;
1009                patch->deflate_origlen = strtoul(buffer + 6, NULL, 10);
1010        }
1011        else if (!strncmp(buffer, "literal ", 8)) {
1012                patch->is_binary = BINARY_LITERAL_DEFLATED;
1013                patch->deflate_origlen = strtoul(buffer + 8, NULL, 10);
1014        }
1015        else
1016                return error("unrecognized binary patch at line %d: %.*s",
1017                             linenr-1, llen-1, buffer);
1018        buffer += llen;
1019        while (1) {
1020                int byte_length, max_byte_length, newsize;
1021                llen = linelen(buffer, size);
1022                used += llen;
1023                linenr++;
1024                if (llen == 1)
1025                        break;
1026                /* Minimum line is "A00000\n" which is 7-byte long,
1027                 * and the line length must be multiple of 5 plus 2.
1028                 */
1029                if ((llen < 7) || (llen-2) % 5)
1030                        goto corrupt;
1031                max_byte_length = (llen - 2) / 5 * 4;
1032                byte_length = *buffer;
1033                if ('A' <= byte_length && byte_length <= 'Z')
1034                        byte_length = byte_length - 'A' + 1;
1035                else if ('a' <= byte_length && byte_length <= 'z')
1036                        byte_length = byte_length - 'a' + 27;
1037                else
1038                        goto corrupt;
1039                /* if the input length was not multiple of 4, we would
1040                 * have filler at the end but the filler should never
1041                 * exceed 3 bytes
1042                 */
1043                if (max_byte_length < byte_length ||
1044                    byte_length <= max_byte_length - 4)
1045                        goto corrupt;
1046                newsize = fragment->size + byte_length;
1047                data = xrealloc(data, newsize);
1048                if (decode_85(data + fragment->size,
1049                              buffer + 1,
1050                              byte_length))
1051                        goto corrupt;
1052                fragment->size = newsize;
1053                buffer += llen;
1054                size -= llen;
1055        }
1056        fragment->patch = data;
1057        return used;
1058 corrupt:
1059        return error("corrupt binary patch at line %d: %.*s",
1060                     linenr-1, llen-1, buffer);
1061}
1062
1063static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1064{
1065        int hdrsize, patchsize;
1066        int offset = find_header(buffer, size, &hdrsize, patch);
1067
1068        if (offset < 0)
1069                return offset;
1070
1071        patchsize = parse_single_patch(buffer + offset + hdrsize, size - offset - hdrsize, patch);
1072
1073        if (!patchsize) {
1074                static const char *binhdr[] = {
1075                        "Binary files ",
1076                        "Files ",
1077                        NULL,
1078                };
1079                static const char git_binary[] = "GIT binary patch\n";
1080                int i;
1081                int hd = hdrsize + offset;
1082                unsigned long llen = linelen(buffer + hd, size - hd);
1083
1084                if (llen == sizeof(git_binary) - 1 &&
1085                    !memcmp(git_binary, buffer + hd, llen)) {
1086                        int used;
1087                        linenr++;
1088                        used = parse_binary(buffer + hd + llen,
1089                                            size - hd - llen, patch);
1090                        if (used)
1091                                patchsize = used + llen;
1092                        else
1093                                patchsize = 0;
1094                }
1095                else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1096                        for (i = 0; binhdr[i]; i++) {
1097                                int len = strlen(binhdr[i]);
1098                                if (len < size - hd &&
1099                                    !memcmp(binhdr[i], buffer + hd, len)) {
1100                                        linenr++;
1101                                        patch->is_binary = 1;
1102                                        patchsize = llen;
1103                                        break;
1104                                }
1105                        }
1106                }
1107
1108                /* Empty patch cannot be applied if:
1109                 * - it is a binary patch and we do not do binary_replace, or
1110                 * - text patch without metadata change
1111                 */
1112                if ((apply || check) &&
1113                    (patch->is_binary
1114                     ? !allow_binary_replacement
1115                     : !metadata_changes(patch)))
1116                        die("patch with only garbage at line %d", linenr);
1117        }
1118
1119        return offset + hdrsize + patchsize;
1120}
1121
1122static const char pluses[] = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1123static const char minuses[]= "----------------------------------------------------------------------";
1124
1125static void show_stats(struct patch *patch)
1126{
1127        const char *prefix = "";
1128        char *name = patch->new_name;
1129        char *qname = NULL;
1130        int len, max, add, del, total;
1131
1132        if (!name)
1133                name = patch->old_name;
1134
1135        if (0 < (len = quote_c_style(name, NULL, NULL, 0))) {
1136                qname = xmalloc(len + 1);
1137                quote_c_style(name, qname, NULL, 0);
1138                name = qname;
1139        }
1140
1141        /*
1142         * "scale" the filename
1143         */
1144        len = strlen(name);
1145        max = max_len;
1146        if (max > 50)
1147                max = 50;
1148        if (len > max) {
1149                char *slash;
1150                prefix = "...";
1151                max -= 3;
1152                name += len - max;
1153                slash = strchr(name, '/');
1154                if (slash)
1155                        name = slash;
1156        }
1157        len = max;
1158
1159        /*
1160         * scale the add/delete
1161         */
1162        max = max_change;
1163        if (max + len > 70)
1164                max = 70 - len;
1165
1166        add = patch->lines_added;
1167        del = patch->lines_deleted;
1168        total = add + del;
1169
1170        if (max_change > 0) {
1171                total = (total * max + max_change / 2) / max_change;
1172                add = (add * max + max_change / 2) / max_change;
1173                del = total - add;
1174        }
1175        if (patch->is_binary)
1176                printf(" %s%-*s |  Bin\n", prefix, len, name);
1177        else
1178                printf(" %s%-*s |%5d %.*s%.*s\n", prefix,
1179                       len, name, patch->lines_added + patch->lines_deleted,
1180                       add, pluses, del, minuses);
1181        if (qname)
1182                free(qname);
1183}
1184
1185static int read_old_data(struct stat *st, const char *path, void *buf, unsigned long size)
1186{
1187        int fd;
1188        unsigned long got;
1189
1190        switch (st->st_mode & S_IFMT) {
1191        case S_IFLNK:
1192                return readlink(path, buf, size);
1193        case S_IFREG:
1194                fd = open(path, O_RDONLY);
1195                if (fd < 0)
1196                        return error("unable to open %s", path);
1197                got = 0;
1198                for (;;) {
1199                        int ret = xread(fd, (char *) buf + got, size - got);
1200                        if (ret <= 0)
1201                                break;
1202                        got += ret;
1203                }
1204                close(fd);
1205                return got;
1206
1207        default:
1208                return -1;
1209        }
1210}
1211
1212static int find_offset(const char *buf, unsigned long size, const char *fragment, unsigned long fragsize, int line, int *lines)
1213{
1214        int i;
1215        unsigned long start, backwards, forwards;
1216
1217        if (fragsize > size)
1218                return -1;
1219
1220        start = 0;
1221        if (line > 1) {
1222                unsigned long offset = 0;
1223                i = line-1;
1224                while (offset + fragsize <= size) {
1225                        if (buf[offset++] == '\n') {
1226                                start = offset;
1227                                if (!--i)
1228                                        break;
1229                        }
1230                }
1231        }
1232
1233        /* Exact line number? */
1234        if (!memcmp(buf + start, fragment, fragsize))
1235                return start;
1236
1237        /*
1238         * There's probably some smart way to do this, but I'll leave
1239         * that to the smart and beautiful people. I'm simple and stupid.
1240         */
1241        backwards = start;
1242        forwards = start;
1243        for (i = 0; ; i++) {
1244                unsigned long try;
1245                int n;
1246
1247                /* "backward" */
1248                if (i & 1) {
1249                        if (!backwards) {
1250                                if (forwards + fragsize > size)
1251                                        break;
1252                                continue;
1253                        }
1254                        do {
1255                                --backwards;
1256                        } while (backwards && buf[backwards-1] != '\n');
1257                        try = backwards;
1258                } else {
1259                        while (forwards + fragsize <= size) {
1260                                if (buf[forwards++] == '\n')
1261                                        break;
1262                        }
1263                        try = forwards;
1264                }
1265
1266                if (try + fragsize > size)
1267                        continue;
1268                if (memcmp(buf + try, fragment, fragsize))
1269                        continue;
1270                n = (i >> 1)+1;
1271                if (i & 1)
1272                        n = -n;
1273                *lines = n;
1274                return try;
1275        }
1276
1277        /*
1278         * We should start searching forward and backward.
1279         */
1280        return -1;
1281}
1282
1283static void remove_first_line(const char **rbuf, int *rsize)
1284{
1285        const char *buf = *rbuf;
1286        int size = *rsize;
1287        unsigned long offset;
1288        offset = 0;
1289        while (offset <= size) {
1290                if (buf[offset++] == '\n')
1291                        break;
1292        }
1293        *rsize = size - offset;
1294        *rbuf = buf + offset;
1295}
1296
1297static void remove_last_line(const char **rbuf, int *rsize)
1298{
1299        const char *buf = *rbuf;
1300        int size = *rsize;
1301        unsigned long offset;
1302        offset = size - 1;
1303        while (offset > 0) {
1304                if (buf[--offset] == '\n')
1305                        break;
1306        }
1307        *rsize = offset + 1;
1308}
1309
1310struct buffer_desc {
1311        char *buffer;
1312        unsigned long size;
1313        unsigned long alloc;
1314};
1315
1316static int apply_line(char *output, const char *patch, int plen)
1317{
1318        /* plen is number of bytes to be copied from patch,
1319         * starting at patch+1 (patch[0] is '+').  Typically
1320         * patch[plen] is '\n'.
1321         */
1322        int add_nl_to_tail = 0;
1323        if ((new_whitespace == strip_whitespace) &&
1324            1 < plen && isspace(patch[plen-1])) {
1325                if (patch[plen] == '\n')
1326                        add_nl_to_tail = 1;
1327                plen--;
1328                while (0 < plen && isspace(patch[plen]))
1329                        plen--;
1330                applied_after_stripping++;
1331        }
1332        memcpy(output, patch + 1, plen);
1333        if (add_nl_to_tail)
1334                output[plen++] = '\n';
1335        return plen;
1336}
1337
1338static int apply_one_fragment(struct buffer_desc *desc, struct fragment *frag,
1339        int inaccurate_eof)
1340{
1341        int match_beginning, match_end;
1342        char *buf = desc->buffer;
1343        const char *patch = frag->patch;
1344        int offset, size = frag->size;
1345        char *old = xmalloc(size);
1346        char *new = xmalloc(size);
1347        const char *oldlines, *newlines;
1348        int oldsize = 0, newsize = 0;
1349        unsigned long leading, trailing;
1350        int pos, lines;
1351
1352        while (size > 0) {
1353                int len = linelen(patch, size);
1354                int plen;
1355
1356                if (!len)
1357                        break;
1358
1359                /*
1360                 * "plen" is how much of the line we should use for
1361                 * the actual patch data. Normally we just remove the
1362                 * first character on the line, but if the line is
1363                 * followed by "\ No newline", then we also remove the
1364                 * last one (which is the newline, of course).
1365                 */
1366                plen = len-1;
1367                if (len < size && patch[len] == '\\')
1368                        plen--;
1369                switch (*patch) {
1370                case ' ':
1371                case '-':
1372                        memcpy(old + oldsize, patch + 1, plen);
1373                        oldsize += plen;
1374                        if (*patch == '-')
1375                                break;
1376                /* Fall-through for ' ' */
1377                case '+':
1378                        if (*patch != '+' || !no_add)
1379                                newsize += apply_line(new + newsize, patch,
1380                                                      plen);
1381                        break;
1382                case '@': case '\\':
1383                        /* Ignore it, we already handled it */
1384                        break;
1385                default:
1386                        return -1;
1387                }
1388                patch += len;
1389                size -= len;
1390        }
1391
1392        if (inaccurate_eof && oldsize > 0 && old[oldsize - 1] == '\n' &&
1393                        newsize > 0 && new[newsize - 1] == '\n') {
1394                oldsize--;
1395                newsize--;
1396        }
1397
1398        oldlines = old;
1399        newlines = new;
1400        leading = frag->leading;
1401        trailing = frag->trailing;
1402
1403        /*
1404         * If we don't have any leading/trailing data in the patch,
1405         * we want it to match at the beginning/end of the file.
1406         */
1407        match_beginning = !leading && (frag->oldpos == 1);
1408        match_end = !trailing;
1409
1410        lines = 0;
1411        pos = frag->newpos;
1412        for (;;) {
1413                offset = find_offset(buf, desc->size, oldlines, oldsize, pos, &lines);
1414                if (match_end && offset + oldsize != desc->size)
1415                        offset = -1;
1416                if (match_beginning && offset)
1417                        offset = -1;
1418                if (offset >= 0) {
1419                        int diff = newsize - oldsize;
1420                        unsigned long size = desc->size + diff;
1421                        unsigned long alloc = desc->alloc;
1422
1423                        /* Warn if it was necessary to reduce the number
1424                         * of context lines.
1425                         */
1426                        if ((leading != frag->leading) || (trailing != frag->trailing))
1427                                fprintf(stderr, "Context reduced to (%ld/%ld) to apply fragment at %d\n",
1428                                        leading, trailing, pos + lines);
1429
1430                        if (size > alloc) {
1431                                alloc = size + 8192;
1432                                desc->alloc = alloc;
1433                                buf = xrealloc(buf, alloc);
1434                                desc->buffer = buf;
1435                        }
1436                        desc->size = size;
1437                        memmove(buf + offset + newsize, buf + offset + oldsize, size - offset - newsize);
1438                        memcpy(buf + offset, newlines, newsize);
1439                        offset = 0;
1440
1441                        break;
1442                }
1443
1444                /* Am I at my context limits? */
1445                if ((leading <= p_context) && (trailing <= p_context))
1446                        break;
1447                if (match_beginning || match_end) {
1448                        match_beginning = match_end = 0;
1449                        continue;
1450                }
1451                /* Reduce the number of context lines
1452                 * Reduce both leading and trailing if they are equal
1453                 * otherwise just reduce the larger context.
1454                 */
1455                if (leading >= trailing) {
1456                        remove_first_line(&oldlines, &oldsize);
1457                        remove_first_line(&newlines, &newsize);
1458                        pos--;
1459                        leading--;
1460                }
1461                if (trailing > leading) {
1462                        remove_last_line(&oldlines, &oldsize);
1463                        remove_last_line(&newlines, &newsize);
1464                        trailing--;
1465                }
1466        }
1467
1468        free(old);
1469        free(new);
1470        return offset;
1471}
1472
1473static char *inflate_it(const void *data, unsigned long size,
1474                        unsigned long inflated_size)
1475{
1476        z_stream stream;
1477        void *out;
1478        int st;
1479
1480        memset(&stream, 0, sizeof(stream));
1481
1482        stream.next_in = (unsigned char *)data;
1483        stream.avail_in = size;
1484        stream.next_out = out = xmalloc(inflated_size);
1485        stream.avail_out = inflated_size;
1486        inflateInit(&stream);
1487        st = inflate(&stream, Z_FINISH);
1488        if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1489                free(out);
1490                return NULL;
1491        }
1492        return out;
1493}
1494
1495static int apply_binary_fragment(struct buffer_desc *desc, struct patch *patch)
1496{
1497        unsigned long dst_size;
1498        struct fragment *fragment = patch->fragments;
1499        void *data;
1500        void *result;
1501
1502        data = inflate_it(fragment->patch, fragment->size,
1503                          patch->deflate_origlen);
1504        if (!data)
1505                return error("corrupt patch data");
1506        switch (patch->is_binary) {
1507        case BINARY_DELTA_DEFLATED:
1508                result = patch_delta(desc->buffer, desc->size,
1509                                     data,
1510                                     patch->deflate_origlen,
1511                                     &dst_size);
1512                free(desc->buffer);
1513                desc->buffer = result;
1514                free(data);
1515                break;
1516        case BINARY_LITERAL_DEFLATED:
1517                free(desc->buffer);
1518                desc->buffer = data;
1519                dst_size = patch->deflate_origlen;
1520                break;
1521        }
1522        if (!desc->buffer)
1523                return -1;
1524        desc->size = desc->alloc = dst_size;
1525        return 0;
1526}
1527
1528static int apply_binary(struct buffer_desc *desc, struct patch *patch)
1529{
1530        const char *name = patch->old_name ? patch->old_name : patch->new_name;
1531        unsigned char sha1[20];
1532        unsigned char hdr[50];
1533        int hdrlen;
1534
1535        if (!allow_binary_replacement)
1536                return error("cannot apply binary patch to '%s' "
1537                             "without --allow-binary-replacement",
1538                             name);
1539
1540        /* For safety, we require patch index line to contain
1541         * full 40-byte textual SHA1 for old and new, at least for now.
1542         */
1543        if (strlen(patch->old_sha1_prefix) != 40 ||
1544            strlen(patch->new_sha1_prefix) != 40 ||
1545            get_sha1_hex(patch->old_sha1_prefix, sha1) ||
1546            get_sha1_hex(patch->new_sha1_prefix, sha1))
1547                return error("cannot apply binary patch to '%s' "
1548                             "without full index line", name);
1549
1550        if (patch->old_name) {
1551                /* See if the old one matches what the patch
1552                 * applies to.
1553                 */
1554                write_sha1_file_prepare(desc->buffer, desc->size,
1555                                        blob_type, sha1, hdr, &hdrlen);
1556                if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
1557                        return error("the patch applies to '%s' (%s), "
1558                                     "which does not match the "
1559                                     "current contents.",
1560                                     name, sha1_to_hex(sha1));
1561        }
1562        else {
1563                /* Otherwise, the old one must be empty. */
1564                if (desc->size)
1565                        return error("the patch applies to an empty "
1566                                     "'%s' but it is not empty", name);
1567        }
1568
1569        get_sha1_hex(patch->new_sha1_prefix, sha1);
1570        if (!memcmp(sha1, null_sha1, 20)) {
1571                free(desc->buffer);
1572                desc->alloc = desc->size = 0;
1573                desc->buffer = NULL;
1574                return 0; /* deletion patch */
1575        }
1576
1577        if (has_sha1_file(sha1)) {
1578                /* We already have the postimage */
1579                char type[10];
1580                unsigned long size;
1581
1582                free(desc->buffer);
1583                desc->buffer = read_sha1_file(sha1, type, &size);
1584                if (!desc->buffer)
1585                        return error("the necessary postimage %s for "
1586                                     "'%s' cannot be read",
1587                                     patch->new_sha1_prefix, name);
1588                desc->alloc = desc->size = size;
1589        }
1590        else {
1591                /* We have verified desc matches the preimage;
1592                 * apply the patch data to it, which is stored
1593                 * in the patch->fragments->{patch,size}.
1594                 */
1595                if (apply_binary_fragment(desc, patch))
1596                        return error("binary patch does not apply to '%s'",
1597                                     name);
1598
1599                /* verify that the result matches */
1600                write_sha1_file_prepare(desc->buffer, desc->size, blob_type,
1601                                        sha1, hdr, &hdrlen);
1602                if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
1603                        return error("binary patch to '%s' creates incorrect result", name);
1604        }
1605
1606        return 0;
1607}
1608
1609static int apply_fragments(struct buffer_desc *desc, struct patch *patch)
1610{
1611        struct fragment *frag = patch->fragments;
1612        const char *name = patch->old_name ? patch->old_name : patch->new_name;
1613
1614        if (patch->is_binary)
1615                return apply_binary(desc, patch);
1616
1617        while (frag) {
1618                if (apply_one_fragment(desc, frag, patch->inaccurate_eof) < 0)
1619                        return error("patch failed: %s:%ld",
1620                                     name, frag->oldpos);
1621                frag = frag->next;
1622        }
1623        return 0;
1624}
1625
1626static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
1627{
1628        char *buf;
1629        unsigned long size, alloc;
1630        struct buffer_desc desc;
1631
1632        size = 0;
1633        alloc = 0;
1634        buf = NULL;
1635        if (cached) {
1636                if (ce) {
1637                        char type[20];
1638                        buf = read_sha1_file(ce->sha1, type, &size);
1639                        if (!buf)
1640                                return error("read of %s failed",
1641                                             patch->old_name);
1642                        alloc = size;
1643                }
1644        }
1645        else if (patch->old_name) {
1646                size = st->st_size;
1647                alloc = size + 8192;
1648                buf = xmalloc(alloc);
1649                if (read_old_data(st, patch->old_name, buf, alloc) != size)
1650                        return error("read of %s failed", patch->old_name);
1651        }
1652
1653        desc.size = size;
1654        desc.alloc = alloc;
1655        desc.buffer = buf;
1656        if (apply_fragments(&desc, patch) < 0)
1657                return -1;
1658        patch->result = desc.buffer;
1659        patch->resultsize = desc.size;
1660
1661        if (patch->is_delete && patch->resultsize)
1662                return error("removal patch leaves file contents");
1663
1664        return 0;
1665}
1666
1667static int check_patch(struct patch *patch)
1668{
1669        struct stat st;
1670        const char *old_name = patch->old_name;
1671        const char *new_name = patch->new_name;
1672        const char *name = old_name ? old_name : new_name;
1673        struct cache_entry *ce = NULL;
1674
1675        if (old_name) {
1676                int changed = 0;
1677                int stat_ret = 0;
1678                unsigned st_mode = 0;
1679
1680                if (!cached)
1681                        stat_ret = lstat(old_name, &st);
1682                if (check_index) {
1683                        int pos = cache_name_pos(old_name, strlen(old_name));
1684                        if (pos < 0)
1685                                return error("%s: does not exist in index",
1686                                             old_name);
1687                        ce = active_cache[pos];
1688                        if (stat_ret < 0) {
1689                                struct checkout costate;
1690                                if (errno != ENOENT)
1691                                        return error("%s: %s", old_name,
1692                                                     strerror(errno));
1693                                /* checkout */
1694                                costate.base_dir = "";
1695                                costate.base_dir_len = 0;
1696                                costate.force = 0;
1697                                costate.quiet = 0;
1698                                costate.not_new = 0;
1699                                costate.refresh_cache = 1;
1700                                if (checkout_entry(ce,
1701                                                   &costate,
1702                                                   NULL) ||
1703                                    lstat(old_name, &st))
1704                                        return -1;
1705                        }
1706                        if (!cached)
1707                                changed = ce_match_stat(ce, &st, 1);
1708                        if (changed)
1709                                return error("%s: does not match index",
1710                                             old_name);
1711                        if (cached)
1712                                st_mode = ntohl(ce->ce_mode);
1713                }
1714                else if (stat_ret < 0)
1715                        return error("%s: %s", old_name, strerror(errno));
1716
1717                if (!cached)
1718                        st_mode = ntohl(create_ce_mode(st.st_mode));
1719
1720                if (patch->is_new < 0)
1721                        patch->is_new = 0;
1722                if (!patch->old_mode)
1723                        patch->old_mode = st_mode;
1724                if ((st_mode ^ patch->old_mode) & S_IFMT)
1725                        return error("%s: wrong type", old_name);
1726                if (st_mode != patch->old_mode)
1727                        fprintf(stderr, "warning: %s has type %o, expected %o\n",
1728                                old_name, st_mode, patch->old_mode);
1729        }
1730
1731        if (new_name && (patch->is_new | patch->is_rename | patch->is_copy)) {
1732                if (check_index && cache_name_pos(new_name, strlen(new_name)) >= 0)
1733                        return error("%s: already exists in index", new_name);
1734                if (!cached) {
1735                        struct stat nst;
1736                        if (!lstat(new_name, &nst)) {
1737                                if (S_ISDIR(nst.st_mode))
1738                                        ; /* ok */
1739                                else
1740                                        return error("%s: already exists in working directory", new_name);
1741                        }
1742                        else if ((errno != ENOENT) && (errno != ENOTDIR))
1743                                return error("%s: %s", new_name, strerror(errno));
1744                }
1745                if (!patch->new_mode) {
1746                        if (patch->is_new)
1747                                patch->new_mode = S_IFREG | 0644;
1748                        else
1749                                patch->new_mode = patch->old_mode;
1750                }
1751        }
1752
1753        if (new_name && old_name) {
1754                int same = !strcmp(old_name, new_name);
1755                if (!patch->new_mode)
1756                        patch->new_mode = patch->old_mode;
1757                if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
1758                        return error("new mode (%o) of %s does not match old mode (%o)%s%s",
1759                                patch->new_mode, new_name, patch->old_mode,
1760                                same ? "" : " of ", same ? "" : old_name);
1761        }
1762
1763        if (apply_data(patch, &st, ce) < 0)
1764                return error("%s: patch does not apply", name);
1765        return 0;
1766}
1767
1768static int check_patch_list(struct patch *patch)
1769{
1770        int error = 0;
1771
1772        for (;patch ; patch = patch->next)
1773                error |= check_patch(patch);
1774        return error;
1775}
1776
1777static inline int is_null_sha1(const unsigned char *sha1)
1778{
1779        return !memcmp(sha1, null_sha1, 20);
1780}
1781
1782static void show_index_list(struct patch *list)
1783{
1784        struct patch *patch;
1785
1786        /* Once we start supporting the reverse patch, it may be
1787         * worth showing the new sha1 prefix, but until then...
1788         */
1789        for (patch = list; patch; patch = patch->next) {
1790                const unsigned char *sha1_ptr;
1791                unsigned char sha1[20];
1792                const char *name;
1793
1794                name = patch->old_name ? patch->old_name : patch->new_name;
1795                if (patch->is_new)
1796                        sha1_ptr = null_sha1;
1797                else if (get_sha1(patch->old_sha1_prefix, sha1))
1798                        die("sha1 information is lacking or useless (%s).",
1799                            name);
1800                else
1801                        sha1_ptr = sha1;
1802
1803                printf("%06o %s ",patch->old_mode, sha1_to_hex(sha1_ptr));
1804                if (line_termination && quote_c_style(name, NULL, NULL, 0))
1805                        quote_c_style(name, NULL, stdout, 0);
1806                else
1807                        fputs(name, stdout);
1808                putchar(line_termination);
1809        }
1810}
1811
1812static void stat_patch_list(struct patch *patch)
1813{
1814        int files, adds, dels;
1815
1816        for (files = adds = dels = 0 ; patch ; patch = patch->next) {
1817                files++;
1818                adds += patch->lines_added;
1819                dels += patch->lines_deleted;
1820                show_stats(patch);
1821        }
1822
1823        printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
1824}
1825
1826static void numstat_patch_list(struct patch *patch)
1827{
1828        for ( ; patch; patch = patch->next) {
1829                const char *name;
1830                name = patch->new_name ? patch->new_name : patch->old_name;
1831                printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
1832                if (line_termination && quote_c_style(name, NULL, NULL, 0))
1833                        quote_c_style(name, NULL, stdout, 0);
1834                else
1835                        fputs(name, stdout);
1836                putchar('\n');
1837        }
1838}
1839
1840static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
1841{
1842        if (mode)
1843                printf(" %s mode %06o %s\n", newdelete, mode, name);
1844        else
1845                printf(" %s %s\n", newdelete, name);
1846}
1847
1848static void show_mode_change(struct patch *p, int show_name)
1849{
1850        if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
1851                if (show_name)
1852                        printf(" mode change %06o => %06o %s\n",
1853                               p->old_mode, p->new_mode, p->new_name);
1854                else
1855                        printf(" mode change %06o => %06o\n",
1856                               p->old_mode, p->new_mode);
1857        }
1858}
1859
1860static void show_rename_copy(struct patch *p)
1861{
1862        const char *renamecopy = p->is_rename ? "rename" : "copy";
1863        const char *old, *new;
1864
1865        /* Find common prefix */
1866        old = p->old_name;
1867        new = p->new_name;
1868        while (1) {
1869                const char *slash_old, *slash_new;
1870                slash_old = strchr(old, '/');
1871                slash_new = strchr(new, '/');
1872                if (!slash_old ||
1873                    !slash_new ||
1874                    slash_old - old != slash_new - new ||
1875                    memcmp(old, new, slash_new - new))
1876                        break;
1877                old = slash_old + 1;
1878                new = slash_new + 1;
1879        }
1880        /* p->old_name thru old is the common prefix, and old and new
1881         * through the end of names are renames
1882         */
1883        if (old != p->old_name)
1884                printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
1885                       (int)(old - p->old_name), p->old_name,
1886                       old, new, p->score);
1887        else
1888                printf(" %s %s => %s (%d%%)\n", renamecopy,
1889                       p->old_name, p->new_name, p->score);
1890        show_mode_change(p, 0);
1891}
1892
1893static void summary_patch_list(struct patch *patch)
1894{
1895        struct patch *p;
1896
1897        for (p = patch; p; p = p->next) {
1898                if (p->is_new)
1899                        show_file_mode_name("create", p->new_mode, p->new_name);
1900                else if (p->is_delete)
1901                        show_file_mode_name("delete", p->old_mode, p->old_name);
1902                else {
1903                        if (p->is_rename || p->is_copy)
1904                                show_rename_copy(p);
1905                        else {
1906                                if (p->score) {
1907                                        printf(" rewrite %s (%d%%)\n",
1908                                               p->new_name, p->score);
1909                                        show_mode_change(p, 0);
1910                                }
1911                                else
1912                                        show_mode_change(p, 1);
1913                        }
1914                }
1915        }
1916}
1917
1918static void patch_stats(struct patch *patch)
1919{
1920        int lines = patch->lines_added + patch->lines_deleted;
1921
1922        if (lines > max_change)
1923                max_change = lines;
1924        if (patch->old_name) {
1925                int len = quote_c_style(patch->old_name, NULL, NULL, 0);
1926                if (!len)
1927                        len = strlen(patch->old_name);
1928                if (len > max_len)
1929                        max_len = len;
1930        }
1931        if (patch->new_name) {
1932                int len = quote_c_style(patch->new_name, NULL, NULL, 0);
1933                if (!len)
1934                        len = strlen(patch->new_name);
1935                if (len > max_len)
1936                        max_len = len;
1937        }
1938}
1939
1940static void remove_file(struct patch *patch)
1941{
1942        if (write_index) {
1943                if (remove_file_from_cache(patch->old_name) < 0)
1944                        die("unable to remove %s from index", patch->old_name);
1945                cache_tree_invalidate_path(active_cache_tree, patch->old_name);
1946        }
1947        if (!cached)
1948                unlink(patch->old_name);
1949}
1950
1951static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
1952{
1953        struct stat st;
1954        struct cache_entry *ce;
1955        int namelen = strlen(path);
1956        unsigned ce_size = cache_entry_size(namelen);
1957
1958        if (!write_index)
1959                return;
1960
1961        ce = xcalloc(1, ce_size);
1962        memcpy(ce->name, path, namelen);
1963        ce->ce_mode = create_ce_mode(mode);
1964        ce->ce_flags = htons(namelen);
1965        if (!cached) {
1966                if (lstat(path, &st) < 0)
1967                        die("unable to stat newly created file %s", path);
1968                fill_stat_cache_info(ce, &st);
1969        }
1970        if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
1971                die("unable to create backing store for newly created file %s", path);
1972        if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
1973                die("unable to add cache entry for %s", path);
1974}
1975
1976static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
1977{
1978        int fd;
1979
1980        if (S_ISLNK(mode))
1981                return symlink(buf, path);
1982        fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
1983        if (fd < 0)
1984                return -1;
1985        while (size) {
1986                int written = xwrite(fd, buf, size);
1987                if (written < 0)
1988                        die("writing file %s: %s", path, strerror(errno));
1989                if (!written)
1990                        die("out of space writing file %s", path);
1991                buf += written;
1992                size -= written;
1993        }
1994        if (close(fd) < 0)
1995                die("closing file %s: %s", path, strerror(errno));
1996        return 0;
1997}
1998
1999/*
2000 * We optimistically assume that the directories exist,
2001 * which is true 99% of the time anyway. If they don't,
2002 * we create them and try again.
2003 */
2004static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
2005{
2006        if (cached)
2007                return;
2008        if (!try_create_file(path, mode, buf, size))
2009                return;
2010
2011        if (errno == ENOENT) {
2012                if (safe_create_leading_directories(path))
2013                        return;
2014                if (!try_create_file(path, mode, buf, size))
2015                        return;
2016        }
2017
2018        if (errno == EEXIST) {
2019                /* We may be trying to create a file where a directory
2020                 * used to be.
2021                 */
2022                struct stat st;
2023                errno = 0;
2024                if (!lstat(path, &st) && S_ISDIR(st.st_mode) && !rmdir(path))
2025                        errno = EEXIST;
2026        }
2027
2028        if (errno == EEXIST) {
2029                unsigned int nr = getpid();
2030
2031                for (;;) {
2032                        const char *newpath;
2033                        newpath = mkpath("%s~%u", path, nr);
2034                        if (!try_create_file(newpath, mode, buf, size)) {
2035                                if (!rename(newpath, path))
2036                                        return;
2037                                unlink(newpath);
2038                                break;
2039                        }
2040                        if (errno != EEXIST)
2041                                break;
2042                        ++nr;
2043                }
2044        }
2045        die("unable to write file %s mode %o", path, mode);
2046}
2047
2048static void create_file(struct patch *patch)
2049{
2050        char *path = patch->new_name;
2051        unsigned mode = patch->new_mode;
2052        unsigned long size = patch->resultsize;
2053        char *buf = patch->result;
2054
2055        if (!mode)
2056                mode = S_IFREG | 0644;
2057        create_one_file(path, mode, buf, size);
2058        add_index_file(path, mode, buf, size);
2059        cache_tree_invalidate_path(active_cache_tree, path);
2060}
2061
2062static void write_out_one_result(struct patch *patch)
2063{
2064        if (patch->is_delete > 0) {
2065                remove_file(patch);
2066                return;
2067        }
2068        if (patch->is_new > 0 || patch->is_copy) {
2069                create_file(patch);
2070                return;
2071        }
2072        /*
2073         * Rename or modification boils down to the same
2074         * thing: remove the old, write the new
2075         */
2076        remove_file(patch);
2077        create_file(patch);
2078}
2079
2080static void write_out_results(struct patch *list, int skipped_patch)
2081{
2082        if (!list && !skipped_patch)
2083                die("No changes");
2084
2085        while (list) {
2086                write_out_one_result(list);
2087                list = list->next;
2088        }
2089}
2090
2091static struct lock_file lock_file;
2092
2093static struct excludes {
2094        struct excludes *next;
2095        const char *path;
2096} *excludes;
2097
2098static int use_patch(struct patch *p)
2099{
2100        const char *pathname = p->new_name ? p->new_name : p->old_name;
2101        struct excludes *x = excludes;
2102        while (x) {
2103                if (fnmatch(x->path, pathname, 0) == 0)
2104                        return 0;
2105                x = x->next;
2106        }
2107        if (0 < prefix_length) {
2108                int pathlen = strlen(pathname);
2109                if (pathlen <= prefix_length ||
2110                    memcmp(prefix, pathname, prefix_length))
2111                        return 0;
2112        }
2113        return 1;
2114}
2115
2116static int apply_patch(int fd, const char *filename, int inaccurate_eof)
2117{
2118        unsigned long offset, size;
2119        char *buffer = read_patch_file(fd, &size);
2120        struct patch *list = NULL, **listp = &list;
2121        int skipped_patch = 0;
2122
2123        patch_input_file = filename;
2124        if (!buffer)
2125                return -1;
2126        offset = 0;
2127        while (size > 0) {
2128                struct patch *patch;
2129                int nr;
2130
2131                patch = xcalloc(1, sizeof(*patch));
2132                patch->inaccurate_eof = inaccurate_eof;
2133                nr = parse_chunk(buffer + offset, size, patch);
2134                if (nr < 0)
2135                        break;
2136                if (use_patch(patch)) {
2137                        patch_stats(patch);
2138                        *listp = patch;
2139                        listp = &patch->next;
2140                } else {
2141                        /* perhaps free it a bit better? */
2142                        free(patch);
2143                        skipped_patch++;
2144                }
2145                offset += nr;
2146                size -= nr;
2147        }
2148
2149        if (whitespace_error && (new_whitespace == error_on_whitespace))
2150                apply = 0;
2151
2152        write_index = check_index && apply;
2153        if (write_index && newfd < 0) {
2154                newfd = hold_lock_file_for_update(&lock_file,
2155                                                  get_index_file());
2156                if (newfd < 0)
2157                        die("unable to create new index file");
2158        }
2159        if (check_index) {
2160                if (read_cache() < 0)
2161                        die("unable to read index file");
2162        }
2163
2164        if ((check || apply) && check_patch_list(list) < 0)
2165                exit(1);
2166
2167        if (apply)
2168                write_out_results(list, skipped_patch);
2169
2170        if (show_index_info)
2171                show_index_list(list);
2172
2173        if (diffstat)
2174                stat_patch_list(list);
2175
2176        if (numstat)
2177                numstat_patch_list(list);
2178
2179        if (summary)
2180                summary_patch_list(list);
2181
2182        free(buffer);
2183        return 0;
2184}
2185
2186static int git_apply_config(const char *var, const char *value)
2187{
2188        if (!strcmp(var, "apply.whitespace")) {
2189                apply_default_whitespace = strdup(value);
2190                return 0;
2191        }
2192        return git_default_config(var, value);
2193}
2194
2195
2196int cmd_apply(int argc, const char **argv, char **envp)
2197{
2198        int i;
2199        int read_stdin = 1;
2200        int inaccurate_eof = 0;
2201
2202        const char *whitespace_option = NULL;
2203
2204        for (i = 1; i < argc; i++) {
2205                const char *arg = argv[i];
2206                char *end;
2207                int fd;
2208
2209                if (!strcmp(arg, "-")) {
2210                        apply_patch(0, "<stdin>", inaccurate_eof);
2211                        read_stdin = 0;
2212                        continue;
2213                }
2214                if (!strncmp(arg, "--exclude=", 10)) {
2215                        struct excludes *x = xmalloc(sizeof(*x));
2216                        x->path = arg + 10;
2217                        x->next = excludes;
2218                        excludes = x;
2219                        continue;
2220                }
2221                if (!strncmp(arg, "-p", 2)) {
2222                        p_value = atoi(arg + 2);
2223                        continue;
2224                }
2225                if (!strcmp(arg, "--no-add")) {
2226                        no_add = 1;
2227                        continue;
2228                }
2229                if (!strcmp(arg, "--stat")) {
2230                        apply = 0;
2231                        diffstat = 1;
2232                        continue;
2233                }
2234                if (!strcmp(arg, "--allow-binary-replacement") ||
2235                    !strcmp(arg, "--binary")) {
2236                        allow_binary_replacement = 1;
2237                        continue;
2238                }
2239                if (!strcmp(arg, "--numstat")) {
2240                        apply = 0;
2241                        numstat = 1;
2242                        continue;
2243                }
2244                if (!strcmp(arg, "--summary")) {
2245                        apply = 0;
2246                        summary = 1;
2247                        continue;
2248                }
2249                if (!strcmp(arg, "--check")) {
2250                        apply = 0;
2251                        check = 1;
2252                        continue;
2253                }
2254                if (!strcmp(arg, "--index")) {
2255                        check_index = 1;
2256                        continue;
2257                }
2258                if (!strcmp(arg, "--cached")) {
2259                        check_index = 1;
2260                        cached = 1;
2261                        continue;
2262                }
2263                if (!strcmp(arg, "--apply")) {
2264                        apply = 1;
2265                        continue;
2266                }
2267                if (!strcmp(arg, "--index-info")) {
2268                        apply = 0;
2269                        show_index_info = 1;
2270                        continue;
2271                }
2272                if (!strcmp(arg, "-z")) {
2273                        line_termination = 0;
2274                        continue;
2275                }
2276                if (!strncmp(arg, "-C", 2)) {
2277                        p_context = strtoul(arg + 2, &end, 0);
2278                        if (*end != '\0')
2279                                die("unrecognized context count '%s'", arg + 2);
2280                        continue;
2281                }
2282                if (!strncmp(arg, "--whitespace=", 13)) {
2283                        whitespace_option = arg + 13;
2284                        parse_whitespace_option(arg + 13);
2285                        continue;
2286                }
2287                if (!strcmp(arg, "--inaccurate-eof")) {
2288                        inaccurate_eof = 1;
2289                        continue;
2290                }
2291
2292                if (check_index && prefix_length < 0) {
2293                        prefix = setup_git_directory();
2294                        prefix_length = prefix ? strlen(prefix) : 0;
2295                        git_config(git_apply_config);
2296                        if (!whitespace_option && apply_default_whitespace)
2297                                parse_whitespace_option(apply_default_whitespace);
2298                }
2299                if (0 < prefix_length)
2300                        arg = prefix_filename(prefix, prefix_length, arg);
2301
2302                fd = open(arg, O_RDONLY);
2303                if (fd < 0)
2304                        usage(apply_usage);
2305                read_stdin = 0;
2306                set_default_whitespace_mode(whitespace_option);
2307                apply_patch(fd, arg, inaccurate_eof);
2308                close(fd);
2309        }
2310        set_default_whitespace_mode(whitespace_option);
2311        if (read_stdin)
2312                apply_patch(0, "<stdin>", inaccurate_eof);
2313        if (whitespace_error) {
2314                if (squelch_whitespace_errors &&
2315                    squelch_whitespace_errors < whitespace_error) {
2316                        int squelched =
2317                                whitespace_error - squelch_whitespace_errors;
2318                        fprintf(stderr, "warning: squelched %d whitespace error%s\n",
2319                                squelched,
2320                                squelched == 1 ? "" : "s");
2321                }
2322                if (new_whitespace == error_on_whitespace)
2323                        die("%d line%s add%s trailing whitespaces.",
2324                            whitespace_error,
2325                            whitespace_error == 1 ? "" : "s",
2326                            whitespace_error == 1 ? "s" : "");
2327                if (applied_after_stripping)
2328                        fprintf(stderr, "warning: %d line%s applied after"
2329                                " stripping trailing whitespaces.\n",
2330                                applied_after_stripping,
2331                                applied_after_stripping == 1 ? "" : "s");
2332                else if (whitespace_error)
2333                        fprintf(stderr, "warning: %d line%s add%s trailing"
2334                                " whitespaces.\n",
2335                                whitespace_error,
2336                                whitespace_error == 1 ? "" : "s",
2337                                whitespace_error == 1 ? "s" : "");
2338        }
2339
2340        if (write_index) {
2341                if (write_cache(newfd, active_cache, active_nr) ||
2342                    close(newfd) || commit_lock_file(&lock_file))
2343                        die("Unable to write new index file");
2344        }
2345
2346        return 0;
2347}