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