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