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