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