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