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