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