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