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