builtin / apply.con commit Merge branch 'mr/hpux' into maint (dd7d0d0)
   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 "string-list.h"
  16#include "dir.h"
  17#include "parse-options.h"
  18
  19/*
  20 *  --check turns on checking that the working tree matches the
  21 *    files that are being modified, but doesn't apply the patch
  22 *  --stat does just a diffstat, and doesn't actually apply
  23 *  --numstat does numeric diffstat, and doesn't actually apply
  24 *  --index-info shows the old and new index info for paths if available.
  25 *  --index updates the cache as well.
  26 *  --cached updates only the cache without ever touching the working tree.
  27 */
  28static const char *prefix;
  29static int prefix_length = -1;
  30static int newfd = -1;
  31
  32static int unidiff_zero;
  33static int p_value = 1;
  34static int p_value_known;
  35static int check_index;
  36static int update_index;
  37static int cached;
  38static int diffstat;
  39static int numstat;
  40static int summary;
  41static int check;
  42static int apply = 1;
  43static int apply_in_reverse;
  44static int apply_with_reject;
  45static int apply_verbosely;
  46static int no_add;
  47static const char *fake_ancestor;
  48static int line_termination = '\n';
  49static unsigned int p_context = UINT_MAX;
  50static const char * const apply_usage[] = {
  51        "git apply [options] [<patch>...]",
  52        NULL
  53};
  54
  55static enum ws_error_action {
  56        nowarn_ws_error,
  57        warn_on_ws_error,
  58        die_on_ws_error,
  59        correct_ws_error
  60} ws_error_action = warn_on_ws_error;
  61static int whitespace_error;
  62static int squelch_whitespace_errors = 5;
  63static int applied_after_fixing_ws;
  64
  65static enum ws_ignore {
  66        ignore_ws_none,
  67        ignore_ws_change
  68} ws_ignore_action = ignore_ws_none;
  69
  70
  71static const char *patch_input_file;
  72static const char *root;
  73static int root_len;
  74static int read_stdin = 1;
  75static int options;
  76
  77static void parse_whitespace_option(const char *option)
  78{
  79        if (!option) {
  80                ws_error_action = warn_on_ws_error;
  81                return;
  82        }
  83        if (!strcmp(option, "warn")) {
  84                ws_error_action = warn_on_ws_error;
  85                return;
  86        }
  87        if (!strcmp(option, "nowarn")) {
  88                ws_error_action = nowarn_ws_error;
  89                return;
  90        }
  91        if (!strcmp(option, "error")) {
  92                ws_error_action = die_on_ws_error;
  93                return;
  94        }
  95        if (!strcmp(option, "error-all")) {
  96                ws_error_action = die_on_ws_error;
  97                squelch_whitespace_errors = 0;
  98                return;
  99        }
 100        if (!strcmp(option, "strip") || !strcmp(option, "fix")) {
 101                ws_error_action = correct_ws_error;
 102                return;
 103        }
 104        die("unrecognized whitespace option '%s'", option);
 105}
 106
 107static void parse_ignorewhitespace_option(const char *option)
 108{
 109        if (!option || !strcmp(option, "no") ||
 110            !strcmp(option, "false") || !strcmp(option, "never") ||
 111            !strcmp(option, "none")) {
 112                ws_ignore_action = ignore_ws_none;
 113                return;
 114        }
 115        if (!strcmp(option, "change")) {
 116                ws_ignore_action = ignore_ws_change;
 117                return;
 118        }
 119        die("unrecognized whitespace ignore option '%s'", option);
 120}
 121
 122static void set_default_whitespace_mode(const char *whitespace_option)
 123{
 124        if (!whitespace_option && !apply_default_whitespace)
 125                ws_error_action = (apply ? warn_on_ws_error : nowarn_ws_error);
 126}
 127
 128/*
 129 * For "diff-stat" like behaviour, we keep track of the biggest change
 130 * we've seen, and the longest filename. That allows us to do simple
 131 * scaling.
 132 */
 133static int max_change, max_len;
 134
 135/*
 136 * Various "current state", notably line numbers and what
 137 * file (and how) we're patching right now.. The "is_xxxx"
 138 * things are flags, where -1 means "don't know yet".
 139 */
 140static int linenr = 1;
 141
 142/*
 143 * This represents one "hunk" from a patch, starting with
 144 * "@@ -oldpos,oldlines +newpos,newlines @@" marker.  The
 145 * patch text is pointed at by patch, and its byte length
 146 * is stored in size.  leading and trailing are the number
 147 * of context lines.
 148 */
 149struct fragment {
 150        unsigned long leading, trailing;
 151        unsigned long oldpos, oldlines;
 152        unsigned long newpos, newlines;
 153        const char *patch;
 154        int size;
 155        int rejected;
 156        int linenr;
 157        struct fragment *next;
 158};
 159
 160/*
 161 * When dealing with a binary patch, we reuse "leading" field
 162 * to store the type of the binary hunk, either deflated "delta"
 163 * or deflated "literal".
 164 */
 165#define binary_patch_method leading
 166#define BINARY_DELTA_DEFLATED   1
 167#define BINARY_LITERAL_DEFLATED 2
 168
 169/*
 170 * This represents a "patch" to a file, both metainfo changes
 171 * such as creation/deletion, filemode and content changes represented
 172 * as a series of fragments.
 173 */
 174struct patch {
 175        char *new_name, *old_name, *def_name;
 176        unsigned int old_mode, new_mode;
 177        int is_new, is_delete;  /* -1 = unknown, 0 = false, 1 = true */
 178        int rejected;
 179        unsigned ws_rule;
 180        unsigned long deflate_origlen;
 181        int lines_added, lines_deleted;
 182        int score;
 183        unsigned int is_toplevel_relative:1;
 184        unsigned int inaccurate_eof:1;
 185        unsigned int is_binary:1;
 186        unsigned int is_copy:1;
 187        unsigned int is_rename:1;
 188        unsigned int recount:1;
 189        struct fragment *fragments;
 190        char *result;
 191        size_t resultsize;
 192        char old_sha1_prefix[41];
 193        char new_sha1_prefix[41];
 194        struct patch *next;
 195};
 196
 197/*
 198 * A line in a file, len-bytes long (includes the terminating LF,
 199 * except for an incomplete line at the end if the file ends with
 200 * one), and its contents hashes to 'hash'.
 201 */
 202struct line {
 203        size_t len;
 204        unsigned hash : 24;
 205        unsigned flag : 8;
 206#define LINE_COMMON     1
 207};
 208
 209/*
 210 * This represents a "file", which is an array of "lines".
 211 */
 212struct image {
 213        char *buf;
 214        size_t len;
 215        size_t nr;
 216        size_t alloc;
 217        struct line *line_allocated;
 218        struct line *line;
 219};
 220
 221/*
 222 * Records filenames that have been touched, in order to handle
 223 * the case where more than one patches touch the same file.
 224 */
 225
 226static struct string_list fn_table;
 227
 228static uint32_t hash_line(const char *cp, size_t len)
 229{
 230        size_t i;
 231        uint32_t h;
 232        for (i = 0, h = 0; i < len; i++) {
 233                if (!isspace(cp[i])) {
 234                        h = h * 3 + (cp[i] & 0xff);
 235                }
 236        }
 237        return h;
 238}
 239
 240/*
 241 * Compare lines s1 of length n1 and s2 of length n2, ignoring
 242 * whitespace difference. Returns 1 if they match, 0 otherwise
 243 */
 244static int fuzzy_matchlines(const char *s1, size_t n1,
 245                            const char *s2, size_t n2)
 246{
 247        const char *last1 = s1 + n1 - 1;
 248        const char *last2 = s2 + n2 - 1;
 249        int result = 0;
 250
 251        if (n1 < 0 || n2 < 0)
 252                return 0;
 253
 254        /* ignore line endings */
 255        while ((*last1 == '\r') || (*last1 == '\n'))
 256                last1--;
 257        while ((*last2 == '\r') || (*last2 == '\n'))
 258                last2--;
 259
 260        /* skip leading whitespace */
 261        while (isspace(*s1) && (s1 <= last1))
 262                s1++;
 263        while (isspace(*s2) && (s2 <= last2))
 264                s2++;
 265        /* early return if both lines are empty */
 266        if ((s1 > last1) && (s2 > last2))
 267                return 1;
 268        while (!result) {
 269                result = *s1++ - *s2++;
 270                /*
 271                 * Skip whitespace inside. We check for whitespace on
 272                 * both buffers because we don't want "a b" to match
 273                 * "ab"
 274                 */
 275                if (isspace(*s1) && isspace(*s2)) {
 276                        while (isspace(*s1) && s1 <= last1)
 277                                s1++;
 278                        while (isspace(*s2) && s2 <= last2)
 279                                s2++;
 280                }
 281                /*
 282                 * If we reached the end on one side only,
 283                 * lines don't match
 284                 */
 285                if (
 286                    ((s2 > last2) && (s1 <= last1)) ||
 287                    ((s1 > last1) && (s2 <= last2)))
 288                        return 0;
 289                if ((s1 > last1) && (s2 > last2))
 290                        break;
 291        }
 292
 293        return !result;
 294}
 295
 296static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
 297{
 298        ALLOC_GROW(img->line_allocated, img->nr + 1, img->alloc);
 299        img->line_allocated[img->nr].len = len;
 300        img->line_allocated[img->nr].hash = hash_line(bol, len);
 301        img->line_allocated[img->nr].flag = flag;
 302        img->nr++;
 303}
 304
 305static void prepare_image(struct image *image, char *buf, size_t len,
 306                          int prepare_linetable)
 307{
 308        const char *cp, *ep;
 309
 310        memset(image, 0, sizeof(*image));
 311        image->buf = buf;
 312        image->len = len;
 313
 314        if (!prepare_linetable)
 315                return;
 316
 317        ep = image->buf + image->len;
 318        cp = image->buf;
 319        while (cp < ep) {
 320                const char *next;
 321                for (next = cp; next < ep && *next != '\n'; next++)
 322                        ;
 323                if (next < ep)
 324                        next++;
 325                add_line_info(image, cp, next - cp, 0);
 326                cp = next;
 327        }
 328        image->line = image->line_allocated;
 329}
 330
 331static void clear_image(struct image *image)
 332{
 333        free(image->buf);
 334        image->buf = NULL;
 335        image->len = 0;
 336}
 337
 338static void say_patch_name(FILE *output, const char *pre,
 339                           struct patch *patch, const char *post)
 340{
 341        fputs(pre, output);
 342        if (patch->old_name && patch->new_name &&
 343            strcmp(patch->old_name, patch->new_name)) {
 344                quote_c_style(patch->old_name, NULL, output, 0);
 345                fputs(" => ", output);
 346                quote_c_style(patch->new_name, NULL, output, 0);
 347        } else {
 348                const char *n = patch->new_name;
 349                if (!n)
 350                        n = patch->old_name;
 351                quote_c_style(n, NULL, output, 0);
 352        }
 353        fputs(post, output);
 354}
 355
 356#define CHUNKSIZE (8192)
 357#define SLOP (16)
 358
 359static void read_patch_file(struct strbuf *sb, int fd)
 360{
 361        if (strbuf_read(sb, fd, 0) < 0)
 362                die_errno("git apply: failed to read");
 363
 364        /*
 365         * Make sure that we have some slop in the buffer
 366         * so that we can do speculative "memcmp" etc, and
 367         * see to it that it is NUL-filled.
 368         */
 369        strbuf_grow(sb, SLOP);
 370        memset(sb->buf + sb->len, 0, SLOP);
 371}
 372
 373static unsigned long linelen(const char *buffer, unsigned long size)
 374{
 375        unsigned long len = 0;
 376        while (size--) {
 377                len++;
 378                if (*buffer++ == '\n')
 379                        break;
 380        }
 381        return len;
 382}
 383
 384static int is_dev_null(const char *str)
 385{
 386        return !memcmp("/dev/null", str, 9) && isspace(str[9]);
 387}
 388
 389#define TERM_SPACE      1
 390#define TERM_TAB        2
 391
 392static int name_terminate(const char *name, int namelen, int c, int terminate)
 393{
 394        if (c == ' ' && !(terminate & TERM_SPACE))
 395                return 0;
 396        if (c == '\t' && !(terminate & TERM_TAB))
 397                return 0;
 398
 399        return 1;
 400}
 401
 402/* remove double slashes to make --index work with such filenames */
 403static char *squash_slash(char *name)
 404{
 405        int i = 0, j = 0;
 406
 407        if (!name)
 408                return NULL;
 409
 410        while (name[i]) {
 411                if ((name[j++] = name[i++]) == '/')
 412                        while (name[i] == '/')
 413                                i++;
 414        }
 415        name[j] = '\0';
 416        return name;
 417}
 418
 419static char *find_name_gnu(const char *line, char *def, int p_value)
 420{
 421        struct strbuf name = STRBUF_INIT;
 422        char *cp;
 423
 424        /*
 425         * Proposed "new-style" GNU patch/diff format; see
 426         * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
 427         */
 428        if (unquote_c_style(&name, line, NULL)) {
 429                strbuf_release(&name);
 430                return NULL;
 431        }
 432
 433        for (cp = name.buf; p_value; p_value--) {
 434                cp = strchr(cp, '/');
 435                if (!cp) {
 436                        strbuf_release(&name);
 437                        return NULL;
 438                }
 439                cp++;
 440        }
 441
 442        /* name can later be freed, so we need
 443         * to memmove, not just return cp
 444         */
 445        strbuf_remove(&name, 0, cp - name.buf);
 446        free(def);
 447        if (root)
 448                strbuf_insert(&name, 0, root, root_len);
 449        return squash_slash(strbuf_detach(&name, NULL));
 450}
 451
 452static size_t sane_tz_len(const char *line, size_t len)
 453{
 454        const char *tz, *p;
 455
 456        if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
 457                return 0;
 458        tz = line + len - strlen(" +0500");
 459
 460        if (tz[1] != '+' && tz[1] != '-')
 461                return 0;
 462
 463        for (p = tz + 2; p != line + len; p++)
 464                if (!isdigit(*p))
 465                        return 0;
 466
 467        return line + len - tz;
 468}
 469
 470static size_t tz_with_colon_len(const char *line, size_t len)
 471{
 472        const char *tz, *p;
 473
 474        if (len < strlen(" +08:00") || line[len - strlen(":00")] != ':')
 475                return 0;
 476        tz = line + len - strlen(" +08:00");
 477
 478        if (tz[0] != ' ' || (tz[1] != '+' && tz[1] != '-'))
 479                return 0;
 480        p = tz + 2;
 481        if (!isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
 482            !isdigit(*p++) || !isdigit(*p++))
 483                return 0;
 484
 485        return line + len - tz;
 486}
 487
 488static size_t date_len(const char *line, size_t len)
 489{
 490        const char *date, *p;
 491
 492        if (len < strlen("72-02-05") || line[len-strlen("-05")] != '-')
 493                return 0;
 494        p = date = line + len - strlen("72-02-05");
 495
 496        if (!isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
 497            !isdigit(*p++) || !isdigit(*p++) || *p++ != '-' ||
 498            !isdigit(*p++) || !isdigit(*p++))   /* Not a date. */
 499                return 0;
 500
 501        if (date - line >= strlen("19") &&
 502            isdigit(date[-1]) && isdigit(date[-2]))     /* 4-digit year */
 503                date -= strlen("19");
 504
 505        return line + len - date;
 506}
 507
 508static size_t short_time_len(const char *line, size_t len)
 509{
 510        const char *time, *p;
 511
 512        if (len < strlen(" 07:01:32") || line[len-strlen(":32")] != ':')
 513                return 0;
 514        p = time = line + len - strlen(" 07:01:32");
 515
 516        /* Permit 1-digit hours? */
 517        if (*p++ != ' ' ||
 518            !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
 519            !isdigit(*p++) || !isdigit(*p++) || *p++ != ':' ||
 520            !isdigit(*p++) || !isdigit(*p++))   /* Not a time. */
 521                return 0;
 522
 523        return line + len - time;
 524}
 525
 526static size_t fractional_time_len(const char *line, size_t len)
 527{
 528        const char *p;
 529        size_t n;
 530
 531        /* Expected format: 19:41:17.620000023 */
 532        if (!len || !isdigit(line[len - 1]))
 533                return 0;
 534        p = line + len - 1;
 535
 536        /* Fractional seconds. */
 537        while (p > line && isdigit(*p))
 538                p--;
 539        if (*p != '.')
 540                return 0;
 541
 542        /* Hours, minutes, and whole seconds. */
 543        n = short_time_len(line, p - line);
 544        if (!n)
 545                return 0;
 546
 547        return line + len - p + n;
 548}
 549
 550static size_t trailing_spaces_len(const char *line, size_t len)
 551{
 552        const char *p;
 553
 554        /* Expected format: ' ' x (1 or more)  */
 555        if (!len || line[len - 1] != ' ')
 556                return 0;
 557
 558        p = line + len;
 559        while (p != line) {
 560                p--;
 561                if (*p != ' ')
 562                        return line + len - (p + 1);
 563        }
 564
 565        /* All spaces! */
 566        return len;
 567}
 568
 569static size_t diff_timestamp_len(const char *line, size_t len)
 570{
 571        const char *end = line + len;
 572        size_t n;
 573
 574        /*
 575         * Posix: 2010-07-05 19:41:17
 576         * GNU: 2010-07-05 19:41:17.620000023 -0500
 577         */
 578
 579        if (!isdigit(end[-1]))
 580                return 0;
 581
 582        n = sane_tz_len(line, end - line);
 583        if (!n)
 584                n = tz_with_colon_len(line, end - line);
 585        end -= n;
 586
 587        n = short_time_len(line, end - line);
 588        if (!n)
 589                n = fractional_time_len(line, end - line);
 590        end -= n;
 591
 592        n = date_len(line, end - line);
 593        if (!n) /* No date.  Too bad. */
 594                return 0;
 595        end -= n;
 596
 597        if (end == line)        /* No space before date. */
 598                return 0;
 599        if (end[-1] == '\t') {  /* Success! */
 600                end--;
 601                return line + len - end;
 602        }
 603        if (end[-1] != ' ')     /* No space before date. */
 604                return 0;
 605
 606        /* Whitespace damage. */
 607        end -= trailing_spaces_len(line, end - line);
 608        return line + len - end;
 609}
 610
 611static char *find_name_common(const char *line, char *def, int p_value,
 612                                const char *end, int terminate)
 613{
 614        int len;
 615        const char *start = NULL;
 616
 617        if (p_value == 0)
 618                start = line;
 619        while (line != end) {
 620                char c = *line;
 621
 622                if (!end && isspace(c)) {
 623                        if (c == '\n')
 624                                break;
 625                        if (name_terminate(start, line-start, c, terminate))
 626                                break;
 627                }
 628                line++;
 629                if (c == '/' && !--p_value)
 630                        start = line;
 631        }
 632        if (!start)
 633                return squash_slash(def);
 634        len = line - start;
 635        if (!len)
 636                return squash_slash(def);
 637
 638        /*
 639         * Generally we prefer the shorter name, especially
 640         * if the other one is just a variation of that with
 641         * something else tacked on to the end (ie "file.orig"
 642         * or "file~").
 643         */
 644        if (def) {
 645                int deflen = strlen(def);
 646                if (deflen < len && !strncmp(start, def, deflen))
 647                        return squash_slash(def);
 648                free(def);
 649        }
 650
 651        if (root) {
 652                char *ret = xmalloc(root_len + len + 1);
 653                strcpy(ret, root);
 654                memcpy(ret + root_len, start, len);
 655                ret[root_len + len] = '\0';
 656                return squash_slash(ret);
 657        }
 658
 659        return squash_slash(xmemdupz(start, len));
 660}
 661
 662static char *find_name(const char *line, char *def, int p_value, int terminate)
 663{
 664        if (*line == '"') {
 665                char *name = find_name_gnu(line, def, p_value);
 666                if (name)
 667                        return name;
 668        }
 669
 670        return find_name_common(line, def, p_value, NULL, terminate);
 671}
 672
 673static char *find_name_traditional(const char *line, char *def, int p_value)
 674{
 675        size_t len = strlen(line);
 676        size_t date_len;
 677
 678        if (*line == '"') {
 679                char *name = find_name_gnu(line, def, p_value);
 680                if (name)
 681                        return name;
 682        }
 683
 684        len = strchrnul(line, '\n') - line;
 685        date_len = diff_timestamp_len(line, len);
 686        if (!date_len)
 687                return find_name_common(line, def, p_value, NULL, TERM_TAB);
 688        len -= date_len;
 689
 690        return find_name_common(line, def, p_value, line + len, 0);
 691}
 692
 693static int count_slashes(const char *cp)
 694{
 695        int cnt = 0;
 696        char ch;
 697
 698        while ((ch = *cp++))
 699                if (ch == '/')
 700                        cnt++;
 701        return cnt;
 702}
 703
 704/*
 705 * Given the string after "--- " or "+++ ", guess the appropriate
 706 * p_value for the given patch.
 707 */
 708static int guess_p_value(const char *nameline)
 709{
 710        char *name, *cp;
 711        int val = -1;
 712
 713        if (is_dev_null(nameline))
 714                return -1;
 715        name = find_name_traditional(nameline, NULL, 0);
 716        if (!name)
 717                return -1;
 718        cp = strchr(name, '/');
 719        if (!cp)
 720                val = 0;
 721        else if (prefix) {
 722                /*
 723                 * Does it begin with "a/$our-prefix" and such?  Then this is
 724                 * very likely to apply to our directory.
 725                 */
 726                if (!strncmp(name, prefix, prefix_length))
 727                        val = count_slashes(prefix);
 728                else {
 729                        cp++;
 730                        if (!strncmp(cp, prefix, prefix_length))
 731                                val = count_slashes(prefix) + 1;
 732                }
 733        }
 734        free(name);
 735        return val;
 736}
 737
 738/*
 739 * Does the ---/+++ line has the POSIX timestamp after the last HT?
 740 * GNU diff puts epoch there to signal a creation/deletion event.  Is
 741 * this such a timestamp?
 742 */
 743static int has_epoch_timestamp(const char *nameline)
 744{
 745        /*
 746         * We are only interested in epoch timestamp; any non-zero
 747         * fraction cannot be one, hence "(\.0+)?" in the regexp below.
 748         * For the same reason, the date must be either 1969-12-31 or
 749         * 1970-01-01, and the seconds part must be "00".
 750         */
 751        const char stamp_regexp[] =
 752                "^(1969-12-31|1970-01-01)"
 753                " "
 754                "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
 755                " "
 756                "([-+][0-2][0-9]:?[0-5][0-9])\n";
 757        const char *timestamp = NULL, *cp, *colon;
 758        static regex_t *stamp;
 759        regmatch_t m[10];
 760        int zoneoffset;
 761        int hourminute;
 762        int status;
 763
 764        for (cp = nameline; *cp != '\n'; cp++) {
 765                if (*cp == '\t')
 766                        timestamp = cp + 1;
 767        }
 768        if (!timestamp)
 769                return 0;
 770        if (!stamp) {
 771                stamp = xmalloc(sizeof(*stamp));
 772                if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
 773                        warning("Cannot prepare timestamp regexp %s",
 774                                stamp_regexp);
 775                        return 0;
 776                }
 777        }
 778
 779        status = regexec(stamp, timestamp, ARRAY_SIZE(m), m, 0);
 780        if (status) {
 781                if (status != REG_NOMATCH)
 782                        warning("regexec returned %d for input: %s",
 783                                status, timestamp);
 784                return 0;
 785        }
 786
 787        zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
 788        if (*colon == ':')
 789                zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
 790        else
 791                zoneoffset = (zoneoffset / 100) * 60 + (zoneoffset % 100);
 792        if (timestamp[m[3].rm_so] == '-')
 793                zoneoffset = -zoneoffset;
 794
 795        /*
 796         * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
 797         * (west of GMT) or 1970-01-01 (east of GMT)
 798         */
 799        if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
 800            (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
 801                return 0;
 802
 803        hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
 804                      strtol(timestamp + 14, NULL, 10) -
 805                      zoneoffset);
 806
 807        return ((zoneoffset < 0 && hourminute == 1440) ||
 808                (0 <= zoneoffset && !hourminute));
 809}
 810
 811/*
 812 * Get the name etc info from the ---/+++ lines of a traditional patch header
 813 *
 814 * FIXME! The end-of-filename heuristics are kind of screwy. For existing
 815 * files, we can happily check the index for a match, but for creating a
 816 * new file we should try to match whatever "patch" does. I have no idea.
 817 */
 818static void parse_traditional_patch(const char *first, const char *second, struct patch *patch)
 819{
 820        char *name;
 821
 822        first += 4;     /* skip "--- " */
 823        second += 4;    /* skip "+++ " */
 824        if (!p_value_known) {
 825                int p, q;
 826                p = guess_p_value(first);
 827                q = guess_p_value(second);
 828                if (p < 0) p = q;
 829                if (0 <= p && p == q) {
 830                        p_value = p;
 831                        p_value_known = 1;
 832                }
 833        }
 834        if (is_dev_null(first)) {
 835                patch->is_new = 1;
 836                patch->is_delete = 0;
 837                name = find_name_traditional(second, NULL, p_value);
 838                patch->new_name = name;
 839        } else if (is_dev_null(second)) {
 840                patch->is_new = 0;
 841                patch->is_delete = 1;
 842                name = find_name_traditional(first, NULL, p_value);
 843                patch->old_name = name;
 844        } else {
 845                name = find_name_traditional(first, NULL, p_value);
 846                name = find_name_traditional(second, name, p_value);
 847                if (has_epoch_timestamp(first)) {
 848                        patch->is_new = 1;
 849                        patch->is_delete = 0;
 850                        patch->new_name = name;
 851                } else if (has_epoch_timestamp(second)) {
 852                        patch->is_new = 0;
 853                        patch->is_delete = 1;
 854                        patch->old_name = name;
 855                } else {
 856                        patch->old_name = patch->new_name = name;
 857                }
 858        }
 859        if (!name)
 860                die("unable to find filename in patch at line %d", linenr);
 861}
 862
 863static int gitdiff_hdrend(const char *line, struct patch *patch)
 864{
 865        return -1;
 866}
 867
 868/*
 869 * We're anal about diff header consistency, to make
 870 * sure that we don't end up having strange ambiguous
 871 * patches floating around.
 872 *
 873 * As a result, gitdiff_{old|new}name() will check
 874 * their names against any previous information, just
 875 * to make sure..
 876 */
 877static char *gitdiff_verify_name(const char *line, int isnull, char *orig_name, const char *oldnew)
 878{
 879        if (!orig_name && !isnull)
 880                return find_name(line, NULL, p_value, TERM_TAB);
 881
 882        if (orig_name) {
 883                int len;
 884                const char *name;
 885                char *another;
 886                name = orig_name;
 887                len = strlen(name);
 888                if (isnull)
 889                        die("git apply: bad git-diff - expected /dev/null, got %s on line %d", name, linenr);
 890                another = find_name(line, NULL, p_value, TERM_TAB);
 891                if (!another || memcmp(another, name, len + 1))
 892                        die("git apply: bad git-diff - inconsistent %s filename on line %d", oldnew, linenr);
 893                free(another);
 894                return orig_name;
 895        }
 896        else {
 897                /* expect "/dev/null" */
 898                if (memcmp("/dev/null", line, 9) || line[9] != '\n')
 899                        die("git apply: bad git-diff - expected /dev/null on line %d", linenr);
 900                return NULL;
 901        }
 902}
 903
 904static int gitdiff_oldname(const char *line, struct patch *patch)
 905{
 906        patch->old_name = gitdiff_verify_name(line, patch->is_new, patch->old_name, "old");
 907        return 0;
 908}
 909
 910static int gitdiff_newname(const char *line, struct patch *patch)
 911{
 912        patch->new_name = gitdiff_verify_name(line, patch->is_delete, patch->new_name, "new");
 913        return 0;
 914}
 915
 916static int gitdiff_oldmode(const char *line, struct patch *patch)
 917{
 918        patch->old_mode = strtoul(line, NULL, 8);
 919        return 0;
 920}
 921
 922static int gitdiff_newmode(const char *line, struct patch *patch)
 923{
 924        patch->new_mode = strtoul(line, NULL, 8);
 925        return 0;
 926}
 927
 928static int gitdiff_delete(const char *line, struct patch *patch)
 929{
 930        patch->is_delete = 1;
 931        patch->old_name = patch->def_name;
 932        return gitdiff_oldmode(line, patch);
 933}
 934
 935static int gitdiff_newfile(const char *line, struct patch *patch)
 936{
 937        patch->is_new = 1;
 938        patch->new_name = patch->def_name;
 939        return gitdiff_newmode(line, patch);
 940}
 941
 942static int gitdiff_copysrc(const char *line, struct patch *patch)
 943{
 944        patch->is_copy = 1;
 945        patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
 946        return 0;
 947}
 948
 949static int gitdiff_copydst(const char *line, struct patch *patch)
 950{
 951        patch->is_copy = 1;
 952        patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
 953        return 0;
 954}
 955
 956static int gitdiff_renamesrc(const char *line, struct patch *patch)
 957{
 958        patch->is_rename = 1;
 959        patch->old_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
 960        return 0;
 961}
 962
 963static int gitdiff_renamedst(const char *line, struct patch *patch)
 964{
 965        patch->is_rename = 1;
 966        patch->new_name = find_name(line, NULL, p_value ? p_value - 1 : 0, 0);
 967        return 0;
 968}
 969
 970static int gitdiff_similarity(const char *line, struct patch *patch)
 971{
 972        if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
 973                patch->score = 0;
 974        return 0;
 975}
 976
 977static int gitdiff_dissimilarity(const char *line, struct patch *patch)
 978{
 979        if ((patch->score = strtoul(line, NULL, 10)) == ULONG_MAX)
 980                patch->score = 0;
 981        return 0;
 982}
 983
 984static int gitdiff_index(const char *line, struct patch *patch)
 985{
 986        /*
 987         * index line is N hexadecimal, "..", N hexadecimal,
 988         * and optional space with octal mode.
 989         */
 990        const char *ptr, *eol;
 991        int len;
 992
 993        ptr = strchr(line, '.');
 994        if (!ptr || ptr[1] != '.' || 40 < ptr - line)
 995                return 0;
 996        len = ptr - line;
 997        memcpy(patch->old_sha1_prefix, line, len);
 998        patch->old_sha1_prefix[len] = 0;
 999
1000        line = ptr + 2;
1001        ptr = strchr(line, ' ');
1002        eol = strchr(line, '\n');
1003
1004        if (!ptr || eol < ptr)
1005                ptr = eol;
1006        len = ptr - line;
1007
1008        if (40 < len)
1009                return 0;
1010        memcpy(patch->new_sha1_prefix, line, len);
1011        patch->new_sha1_prefix[len] = 0;
1012        if (*ptr == ' ')
1013                patch->old_mode = strtoul(ptr+1, NULL, 8);
1014        return 0;
1015}
1016
1017/*
1018 * This is normal for a diff that doesn't change anything: we'll fall through
1019 * into the next diff. Tell the parser to break out.
1020 */
1021static int gitdiff_unrecognized(const char *line, struct patch *patch)
1022{
1023        return -1;
1024}
1025
1026static const char *stop_at_slash(const char *line, int llen)
1027{
1028        int nslash = p_value;
1029        int i;
1030
1031        for (i = 0; i < llen; i++) {
1032                int ch = line[i];
1033                if (ch == '/' && --nslash <= 0)
1034                        return &line[i];
1035        }
1036        return NULL;
1037}
1038
1039/*
1040 * This is to extract the same name that appears on "diff --git"
1041 * line.  We do not find and return anything if it is a rename
1042 * patch, and it is OK because we will find the name elsewhere.
1043 * We need to reliably find name only when it is mode-change only,
1044 * creation or deletion of an empty file.  In any of these cases,
1045 * both sides are the same name under a/ and b/ respectively.
1046 */
1047static char *git_header_name(char *line, int llen)
1048{
1049        const char *name;
1050        const char *second = NULL;
1051        size_t len, line_len;
1052
1053        line += strlen("diff --git ");
1054        llen -= strlen("diff --git ");
1055
1056        if (*line == '"') {
1057                const char *cp;
1058                struct strbuf first = STRBUF_INIT;
1059                struct strbuf sp = STRBUF_INIT;
1060
1061                if (unquote_c_style(&first, line, &second))
1062                        goto free_and_fail1;
1063
1064                /* advance to the first slash */
1065                cp = stop_at_slash(first.buf, first.len);
1066                /* we do not accept absolute paths */
1067                if (!cp || cp == first.buf)
1068                        goto free_and_fail1;
1069                strbuf_remove(&first, 0, cp + 1 - first.buf);
1070
1071                /*
1072                 * second points at one past closing dq of name.
1073                 * find the second name.
1074                 */
1075                while ((second < line + llen) && isspace(*second))
1076                        second++;
1077
1078                if (line + llen <= second)
1079                        goto free_and_fail1;
1080                if (*second == '"') {
1081                        if (unquote_c_style(&sp, second, NULL))
1082                                goto free_and_fail1;
1083                        cp = stop_at_slash(sp.buf, sp.len);
1084                        if (!cp || cp == sp.buf)
1085                                goto free_and_fail1;
1086                        /* They must match, otherwise ignore */
1087                        if (strcmp(cp + 1, first.buf))
1088                                goto free_and_fail1;
1089                        strbuf_release(&sp);
1090                        return strbuf_detach(&first, NULL);
1091                }
1092
1093                /* unquoted second */
1094                cp = stop_at_slash(second, line + llen - second);
1095                if (!cp || cp == second)
1096                        goto free_and_fail1;
1097                cp++;
1098                if (line + llen - cp != first.len + 1 ||
1099                    memcmp(first.buf, cp, first.len))
1100                        goto free_and_fail1;
1101                return strbuf_detach(&first, NULL);
1102
1103        free_and_fail1:
1104                strbuf_release(&first);
1105                strbuf_release(&sp);
1106                return NULL;
1107        }
1108
1109        /* unquoted first name */
1110        name = stop_at_slash(line, llen);
1111        if (!name || name == line)
1112                return NULL;
1113        name++;
1114
1115        /*
1116         * since the first name is unquoted, a dq if exists must be
1117         * the beginning of the second name.
1118         */
1119        for (second = name; second < line + llen; second++) {
1120                if (*second == '"') {
1121                        struct strbuf sp = STRBUF_INIT;
1122                        const char *np;
1123
1124                        if (unquote_c_style(&sp, second, NULL))
1125                                goto free_and_fail2;
1126
1127                        np = stop_at_slash(sp.buf, sp.len);
1128                        if (!np || np == sp.buf)
1129                                goto free_and_fail2;
1130                        np++;
1131
1132                        len = sp.buf + sp.len - np;
1133                        if (len < second - name &&
1134                            !strncmp(np, name, len) &&
1135                            isspace(name[len])) {
1136                                /* Good */
1137                                strbuf_remove(&sp, 0, np - sp.buf);
1138                                return strbuf_detach(&sp, NULL);
1139                        }
1140
1141                free_and_fail2:
1142                        strbuf_release(&sp);
1143                        return NULL;
1144                }
1145        }
1146
1147        /*
1148         * Accept a name only if it shows up twice, exactly the same
1149         * form.
1150         */
1151        second = strchr(name, '\n');
1152        if (!second)
1153                return NULL;
1154        line_len = second - name;
1155        for (len = 0 ; ; len++) {
1156                switch (name[len]) {
1157                default:
1158                        continue;
1159                case '\n':
1160                        return NULL;
1161                case '\t': case ' ':
1162                        second = stop_at_slash(name + len, line_len - len);
1163                        if (!second)
1164                                return NULL;
1165                        second++;
1166                        if (second[len] == '\n' && !strncmp(name, second, len)) {
1167                                return xmemdupz(name, len);
1168                        }
1169                }
1170        }
1171}
1172
1173/* Verify that we recognize the lines following a git header */
1174static int parse_git_header(char *line, int len, unsigned int size, struct patch *patch)
1175{
1176        unsigned long offset;
1177
1178        /* A git diff has explicit new/delete information, so we don't guess */
1179        patch->is_new = 0;
1180        patch->is_delete = 0;
1181
1182        /*
1183         * Some things may not have the old name in the
1184         * rest of the headers anywhere (pure mode changes,
1185         * or removing or adding empty files), so we get
1186         * the default name from the header.
1187         */
1188        patch->def_name = git_header_name(line, len);
1189        if (patch->def_name && root) {
1190                char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
1191                strcpy(s, root);
1192                strcpy(s + root_len, patch->def_name);
1193                free(patch->def_name);
1194                patch->def_name = s;
1195        }
1196
1197        line += len;
1198        size -= len;
1199        linenr++;
1200        for (offset = len ; size > 0 ; offset += len, size -= len, line += len, linenr++) {
1201                static const struct opentry {
1202                        const char *str;
1203                        int (*fn)(const char *, struct patch *);
1204                } optable[] = {
1205                        { "@@ -", gitdiff_hdrend },
1206                        { "--- ", gitdiff_oldname },
1207                        { "+++ ", gitdiff_newname },
1208                        { "old mode ", gitdiff_oldmode },
1209                        { "new mode ", gitdiff_newmode },
1210                        { "deleted file mode ", gitdiff_delete },
1211                        { "new file mode ", gitdiff_newfile },
1212                        { "copy from ", gitdiff_copysrc },
1213                        { "copy to ", gitdiff_copydst },
1214                        { "rename old ", gitdiff_renamesrc },
1215                        { "rename new ", gitdiff_renamedst },
1216                        { "rename from ", gitdiff_renamesrc },
1217                        { "rename to ", gitdiff_renamedst },
1218                        { "similarity index ", gitdiff_similarity },
1219                        { "dissimilarity index ", gitdiff_dissimilarity },
1220                        { "index ", gitdiff_index },
1221                        { "", gitdiff_unrecognized },
1222                };
1223                int i;
1224
1225                len = linelen(line, size);
1226                if (!len || line[len-1] != '\n')
1227                        break;
1228                for (i = 0; i < ARRAY_SIZE(optable); i++) {
1229                        const struct opentry *p = optable + i;
1230                        int oplen = strlen(p->str);
1231                        if (len < oplen || memcmp(p->str, line, oplen))
1232                                continue;
1233                        if (p->fn(line + oplen, patch) < 0)
1234                                return offset;
1235                        break;
1236                }
1237        }
1238
1239        return offset;
1240}
1241
1242static int parse_num(const char *line, unsigned long *p)
1243{
1244        char *ptr;
1245
1246        if (!isdigit(*line))
1247                return 0;
1248        *p = strtoul(line, &ptr, 10);
1249        return ptr - line;
1250}
1251
1252static int parse_range(const char *line, int len, int offset, const char *expect,
1253                       unsigned long *p1, unsigned long *p2)
1254{
1255        int digits, ex;
1256
1257        if (offset < 0 || offset >= len)
1258                return -1;
1259        line += offset;
1260        len -= offset;
1261
1262        digits = parse_num(line, p1);
1263        if (!digits)
1264                return -1;
1265
1266        offset += digits;
1267        line += digits;
1268        len -= digits;
1269
1270        *p2 = 1;
1271        if (*line == ',') {
1272                digits = parse_num(line+1, p2);
1273                if (!digits)
1274                        return -1;
1275
1276                offset += digits+1;
1277                line += digits+1;
1278                len -= digits+1;
1279        }
1280
1281        ex = strlen(expect);
1282        if (ex > len)
1283                return -1;
1284        if (memcmp(line, expect, ex))
1285                return -1;
1286
1287        return offset + ex;
1288}
1289
1290static void recount_diff(char *line, int size, struct fragment *fragment)
1291{
1292        int oldlines = 0, newlines = 0, ret = 0;
1293
1294        if (size < 1) {
1295                warning("recount: ignore empty hunk");
1296                return;
1297        }
1298
1299        for (;;) {
1300                int len = linelen(line, size);
1301                size -= len;
1302                line += len;
1303
1304                if (size < 1)
1305                        break;
1306
1307                switch (*line) {
1308                case ' ': case '\n':
1309                        newlines++;
1310                        /* fall through */
1311                case '-':
1312                        oldlines++;
1313                        continue;
1314                case '+':
1315                        newlines++;
1316                        continue;
1317                case '\\':
1318                        continue;
1319                case '@':
1320                        ret = size < 3 || prefixcmp(line, "@@ ");
1321                        break;
1322                case 'd':
1323                        ret = size < 5 || prefixcmp(line, "diff ");
1324                        break;
1325                default:
1326                        ret = -1;
1327                        break;
1328                }
1329                if (ret) {
1330                        warning("recount: unexpected line: %.*s",
1331                                (int)linelen(line, size), line);
1332                        return;
1333                }
1334                break;
1335        }
1336        fragment->oldlines = oldlines;
1337        fragment->newlines = newlines;
1338}
1339
1340/*
1341 * Parse a unified diff fragment header of the
1342 * form "@@ -a,b +c,d @@"
1343 */
1344static int parse_fragment_header(char *line, int len, struct fragment *fragment)
1345{
1346        int offset;
1347
1348        if (!len || line[len-1] != '\n')
1349                return -1;
1350
1351        /* Figure out the number of lines in a fragment */
1352        offset = parse_range(line, len, 4, " +", &fragment->oldpos, &fragment->oldlines);
1353        offset = parse_range(line, len, offset, " @@", &fragment->newpos, &fragment->newlines);
1354
1355        return offset;
1356}
1357
1358static int find_header(char *line, unsigned long size, int *hdrsize, struct patch *patch)
1359{
1360        unsigned long offset, len;
1361
1362        patch->is_toplevel_relative = 0;
1363        patch->is_rename = patch->is_copy = 0;
1364        patch->is_new = patch->is_delete = -1;
1365        patch->old_mode = patch->new_mode = 0;
1366        patch->old_name = patch->new_name = NULL;
1367        for (offset = 0; size > 0; offset += len, size -= len, line += len, linenr++) {
1368                unsigned long nextlen;
1369
1370                len = linelen(line, size);
1371                if (!len)
1372                        break;
1373
1374                /* Testing this early allows us to take a few shortcuts.. */
1375                if (len < 6)
1376                        continue;
1377
1378                /*
1379                 * Make sure we don't find any unconnected patch fragments.
1380                 * That's a sign that we didn't find a header, and that a
1381                 * patch has become corrupted/broken up.
1382                 */
1383                if (!memcmp("@@ -", line, 4)) {
1384                        struct fragment dummy;
1385                        if (parse_fragment_header(line, len, &dummy) < 0)
1386                                continue;
1387                        die("patch fragment without header at line %d: %.*s",
1388                            linenr, (int)len-1, line);
1389                }
1390
1391                if (size < len + 6)
1392                        break;
1393
1394                /*
1395                 * Git patch? It might not have a real patch, just a rename
1396                 * or mode change, so we handle that specially
1397                 */
1398                if (!memcmp("diff --git ", line, 11)) {
1399                        int git_hdr_len = parse_git_header(line, len, size, patch);
1400                        if (git_hdr_len <= len)
1401                                continue;
1402                        if (!patch->old_name && !patch->new_name) {
1403                                if (!patch->def_name)
1404                                        die("git diff header lacks filename information when removing "
1405                                            "%d leading pathname components (line %d)" , p_value, linenr);
1406                                patch->old_name = patch->new_name = patch->def_name;
1407                        }
1408                        patch->is_toplevel_relative = 1;
1409                        *hdrsize = git_hdr_len;
1410                        return offset;
1411                }
1412
1413                /* --- followed by +++ ? */
1414                if (memcmp("--- ", line,  4) || memcmp("+++ ", line + len, 4))
1415                        continue;
1416
1417                /*
1418                 * We only accept unified patches, so we want it to
1419                 * at least have "@@ -a,b +c,d @@\n", which is 14 chars
1420                 * minimum ("@@ -0,0 +1 @@\n" is the shortest).
1421                 */
1422                nextlen = linelen(line + len, size - len);
1423                if (size < nextlen + 14 || memcmp("@@ -", line + len + nextlen, 4))
1424                        continue;
1425
1426                /* Ok, we'll consider it a patch */
1427                parse_traditional_patch(line, line+len, patch);
1428                *hdrsize = len + nextlen;
1429                linenr += 2;
1430                return offset;
1431        }
1432        return -1;
1433}
1434
1435static void record_ws_error(unsigned result, const char *line, int len, int linenr)
1436{
1437        char *err;
1438
1439        if (!result)
1440                return;
1441
1442        whitespace_error++;
1443        if (squelch_whitespace_errors &&
1444            squelch_whitespace_errors < whitespace_error)
1445                return;
1446
1447        err = whitespace_error_string(result);
1448        fprintf(stderr, "%s:%d: %s.\n%.*s\n",
1449                patch_input_file, linenr, err, len, line);
1450        free(err);
1451}
1452
1453static void check_whitespace(const char *line, int len, unsigned ws_rule)
1454{
1455        unsigned result = ws_check(line + 1, len - 1, ws_rule);
1456
1457        record_ws_error(result, line + 1, len - 2, linenr);
1458}
1459
1460/*
1461 * Parse a unified diff. Note that this really needs to parse each
1462 * fragment separately, since the only way to know the difference
1463 * between a "---" that is part of a patch, and a "---" that starts
1464 * the next patch is to look at the line counts..
1465 */
1466static int parse_fragment(char *line, unsigned long size,
1467                          struct patch *patch, struct fragment *fragment)
1468{
1469        int added, deleted;
1470        int len = linelen(line, size), offset;
1471        unsigned long oldlines, newlines;
1472        unsigned long leading, trailing;
1473
1474        offset = parse_fragment_header(line, len, fragment);
1475        if (offset < 0)
1476                return -1;
1477        if (offset > 0 && patch->recount)
1478                recount_diff(line + offset, size - offset, fragment);
1479        oldlines = fragment->oldlines;
1480        newlines = fragment->newlines;
1481        leading = 0;
1482        trailing = 0;
1483
1484        /* Parse the thing.. */
1485        line += len;
1486        size -= len;
1487        linenr++;
1488        added = deleted = 0;
1489        for (offset = len;
1490             0 < size;
1491             offset += len, size -= len, line += len, linenr++) {
1492                if (!oldlines && !newlines)
1493                        break;
1494                len = linelen(line, size);
1495                if (!len || line[len-1] != '\n')
1496                        return -1;
1497                switch (*line) {
1498                default:
1499                        return -1;
1500                case '\n': /* newer GNU diff, an empty context line */
1501                case ' ':
1502                        oldlines--;
1503                        newlines--;
1504                        if (!deleted && !added)
1505                                leading++;
1506                        trailing++;
1507                        break;
1508                case '-':
1509                        if (apply_in_reverse &&
1510                            ws_error_action != nowarn_ws_error)
1511                                check_whitespace(line, len, patch->ws_rule);
1512                        deleted++;
1513                        oldlines--;
1514                        trailing = 0;
1515                        break;
1516                case '+':
1517                        if (!apply_in_reverse &&
1518                            ws_error_action != nowarn_ws_error)
1519                                check_whitespace(line, len, patch->ws_rule);
1520                        added++;
1521                        newlines--;
1522                        trailing = 0;
1523                        break;
1524
1525                /*
1526                 * We allow "\ No newline at end of file". Depending
1527                 * on locale settings when the patch was produced we
1528                 * don't know what this line looks like. The only
1529                 * thing we do know is that it begins with "\ ".
1530                 * Checking for 12 is just for sanity check -- any
1531                 * l10n of "\ No newline..." is at least that long.
1532                 */
1533                case '\\':
1534                        if (len < 12 || memcmp(line, "\\ ", 2))
1535                                return -1;
1536                        break;
1537                }
1538        }
1539        if (oldlines || newlines)
1540                return -1;
1541        fragment->leading = leading;
1542        fragment->trailing = trailing;
1543
1544        /*
1545         * If a fragment ends with an incomplete line, we failed to include
1546         * it in the above loop because we hit oldlines == newlines == 0
1547         * before seeing it.
1548         */
1549        if (12 < size && !memcmp(line, "\\ ", 2))
1550                offset += linelen(line, size);
1551
1552        patch->lines_added += added;
1553        patch->lines_deleted += deleted;
1554
1555        if (0 < patch->is_new && oldlines)
1556                return error("new file depends on old contents");
1557        if (0 < patch->is_delete && newlines)
1558                return error("deleted file still has contents");
1559        return offset;
1560}
1561
1562static int parse_single_patch(char *line, unsigned long size, struct patch *patch)
1563{
1564        unsigned long offset = 0;
1565        unsigned long oldlines = 0, newlines = 0, context = 0;
1566        struct fragment **fragp = &patch->fragments;
1567
1568        while (size > 4 && !memcmp(line, "@@ -", 4)) {
1569                struct fragment *fragment;
1570                int len;
1571
1572                fragment = xcalloc(1, sizeof(*fragment));
1573                fragment->linenr = linenr;
1574                len = parse_fragment(line, size, patch, fragment);
1575                if (len <= 0)
1576                        die("corrupt patch at line %d", linenr);
1577                fragment->patch = line;
1578                fragment->size = len;
1579                oldlines += fragment->oldlines;
1580                newlines += fragment->newlines;
1581                context += fragment->leading + fragment->trailing;
1582
1583                *fragp = fragment;
1584                fragp = &fragment->next;
1585
1586                offset += len;
1587                line += len;
1588                size -= len;
1589        }
1590
1591        /*
1592         * If something was removed (i.e. we have old-lines) it cannot
1593         * be creation, and if something was added it cannot be
1594         * deletion.  However, the reverse is not true; --unified=0
1595         * patches that only add are not necessarily creation even
1596         * though they do not have any old lines, and ones that only
1597         * delete are not necessarily deletion.
1598         *
1599         * Unfortunately, a real creation/deletion patch do _not_ have
1600         * any context line by definition, so we cannot safely tell it
1601         * apart with --unified=0 insanity.  At least if the patch has
1602         * more than one hunk it is not creation or deletion.
1603         */
1604        if (patch->is_new < 0 &&
1605            (oldlines || (patch->fragments && patch->fragments->next)))
1606                patch->is_new = 0;
1607        if (patch->is_delete < 0 &&
1608            (newlines || (patch->fragments && patch->fragments->next)))
1609                patch->is_delete = 0;
1610
1611        if (0 < patch->is_new && oldlines)
1612                die("new file %s depends on old contents", patch->new_name);
1613        if (0 < patch->is_delete && newlines)
1614                die("deleted file %s still has contents", patch->old_name);
1615        if (!patch->is_delete && !newlines && context)
1616                fprintf(stderr, "** warning: file %s becomes empty but "
1617                        "is not deleted\n", patch->new_name);
1618
1619        return offset;
1620}
1621
1622static inline int metadata_changes(struct patch *patch)
1623{
1624        return  patch->is_rename > 0 ||
1625                patch->is_copy > 0 ||
1626                patch->is_new > 0 ||
1627                patch->is_delete ||
1628                (patch->old_mode && patch->new_mode &&
1629                 patch->old_mode != patch->new_mode);
1630}
1631
1632static char *inflate_it(const void *data, unsigned long size,
1633                        unsigned long inflated_size)
1634{
1635        z_stream stream;
1636        void *out;
1637        int st;
1638
1639        memset(&stream, 0, sizeof(stream));
1640
1641        stream.next_in = (unsigned char *)data;
1642        stream.avail_in = size;
1643        stream.next_out = out = xmalloc(inflated_size);
1644        stream.avail_out = inflated_size;
1645        git_inflate_init(&stream);
1646        st = git_inflate(&stream, Z_FINISH);
1647        git_inflate_end(&stream);
1648        if ((st != Z_STREAM_END) || stream.total_out != inflated_size) {
1649                free(out);
1650                return NULL;
1651        }
1652        return out;
1653}
1654
1655static struct fragment *parse_binary_hunk(char **buf_p,
1656                                          unsigned long *sz_p,
1657                                          int *status_p,
1658                                          int *used_p)
1659{
1660        /*
1661         * Expect a line that begins with binary patch method ("literal"
1662         * or "delta"), followed by the length of data before deflating.
1663         * a sequence of 'length-byte' followed by base-85 encoded data
1664         * should follow, terminated by a newline.
1665         *
1666         * Each 5-byte sequence of base-85 encodes up to 4 bytes,
1667         * and we would limit the patch line to 66 characters,
1668         * so one line can fit up to 13 groups that would decode
1669         * to 52 bytes max.  The length byte 'A'-'Z' corresponds
1670         * to 1-26 bytes, and 'a'-'z' corresponds to 27-52 bytes.
1671         */
1672        int llen, used;
1673        unsigned long size = *sz_p;
1674        char *buffer = *buf_p;
1675        int patch_method;
1676        unsigned long origlen;
1677        char *data = NULL;
1678        int hunk_size = 0;
1679        struct fragment *frag;
1680
1681        llen = linelen(buffer, size);
1682        used = llen;
1683
1684        *status_p = 0;
1685
1686        if (!prefixcmp(buffer, "delta ")) {
1687                patch_method = BINARY_DELTA_DEFLATED;
1688                origlen = strtoul(buffer + 6, NULL, 10);
1689        }
1690        else if (!prefixcmp(buffer, "literal ")) {
1691                patch_method = BINARY_LITERAL_DEFLATED;
1692                origlen = strtoul(buffer + 8, NULL, 10);
1693        }
1694        else
1695                return NULL;
1696
1697        linenr++;
1698        buffer += llen;
1699        while (1) {
1700                int byte_length, max_byte_length, newsize;
1701                llen = linelen(buffer, size);
1702                used += llen;
1703                linenr++;
1704                if (llen == 1) {
1705                        /* consume the blank line */
1706                        buffer++;
1707                        size--;
1708                        break;
1709                }
1710                /*
1711                 * Minimum line is "A00000\n" which is 7-byte long,
1712                 * and the line length must be multiple of 5 plus 2.
1713                 */
1714                if ((llen < 7) || (llen-2) % 5)
1715                        goto corrupt;
1716                max_byte_length = (llen - 2) / 5 * 4;
1717                byte_length = *buffer;
1718                if ('A' <= byte_length && byte_length <= 'Z')
1719                        byte_length = byte_length - 'A' + 1;
1720                else if ('a' <= byte_length && byte_length <= 'z')
1721                        byte_length = byte_length - 'a' + 27;
1722                else
1723                        goto corrupt;
1724                /* if the input length was not multiple of 4, we would
1725                 * have filler at the end but the filler should never
1726                 * exceed 3 bytes
1727                 */
1728                if (max_byte_length < byte_length ||
1729                    byte_length <= max_byte_length - 4)
1730                        goto corrupt;
1731                newsize = hunk_size + byte_length;
1732                data = xrealloc(data, newsize);
1733                if (decode_85(data + hunk_size, buffer + 1, byte_length))
1734                        goto corrupt;
1735                hunk_size = newsize;
1736                buffer += llen;
1737                size -= llen;
1738        }
1739
1740        frag = xcalloc(1, sizeof(*frag));
1741        frag->patch = inflate_it(data, hunk_size, origlen);
1742        if (!frag->patch)
1743                goto corrupt;
1744        free(data);
1745        frag->size = origlen;
1746        *buf_p = buffer;
1747        *sz_p = size;
1748        *used_p = used;
1749        frag->binary_patch_method = patch_method;
1750        return frag;
1751
1752 corrupt:
1753        free(data);
1754        *status_p = -1;
1755        error("corrupt binary patch at line %d: %.*s",
1756              linenr-1, llen-1, buffer);
1757        return NULL;
1758}
1759
1760static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
1761{
1762        /*
1763         * We have read "GIT binary patch\n"; what follows is a line
1764         * that says the patch method (currently, either "literal" or
1765         * "delta") and the length of data before deflating; a
1766         * sequence of 'length-byte' followed by base-85 encoded data
1767         * follows.
1768         *
1769         * When a binary patch is reversible, there is another binary
1770         * hunk in the same format, starting with patch method (either
1771         * "literal" or "delta") with the length of data, and a sequence
1772         * of length-byte + base-85 encoded data, terminated with another
1773         * empty line.  This data, when applied to the postimage, produces
1774         * the preimage.
1775         */
1776        struct fragment *forward;
1777        struct fragment *reverse;
1778        int status;
1779        int used, used_1;
1780
1781        forward = parse_binary_hunk(&buffer, &size, &status, &used);
1782        if (!forward && !status)
1783                /* there has to be one hunk (forward hunk) */
1784                return error("unrecognized binary patch at line %d", linenr-1);
1785        if (status)
1786                /* otherwise we already gave an error message */
1787                return status;
1788
1789        reverse = parse_binary_hunk(&buffer, &size, &status, &used_1);
1790        if (reverse)
1791                used += used_1;
1792        else if (status) {
1793                /*
1794                 * Not having reverse hunk is not an error, but having
1795                 * a corrupt reverse hunk is.
1796                 */
1797                free((void*) forward->patch);
1798                free(forward);
1799                return status;
1800        }
1801        forward->next = reverse;
1802        patch->fragments = forward;
1803        patch->is_binary = 1;
1804        return used;
1805}
1806
1807static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
1808{
1809        int hdrsize, patchsize;
1810        int offset = find_header(buffer, size, &hdrsize, patch);
1811
1812        if (offset < 0)
1813                return offset;
1814
1815        patch->ws_rule = whitespace_rule(patch->new_name
1816                                         ? patch->new_name
1817                                         : patch->old_name);
1818
1819        patchsize = parse_single_patch(buffer + offset + hdrsize,
1820                                       size - offset - hdrsize, patch);
1821
1822        if (!patchsize) {
1823                static const char *binhdr[] = {
1824                        "Binary files ",
1825                        "Files ",
1826                        NULL,
1827                };
1828                static const char git_binary[] = "GIT binary patch\n";
1829                int i;
1830                int hd = hdrsize + offset;
1831                unsigned long llen = linelen(buffer + hd, size - hd);
1832
1833                if (llen == sizeof(git_binary) - 1 &&
1834                    !memcmp(git_binary, buffer + hd, llen)) {
1835                        int used;
1836                        linenr++;
1837                        used = parse_binary(buffer + hd + llen,
1838                                            size - hd - llen, patch);
1839                        if (used)
1840                                patchsize = used + llen;
1841                        else
1842                                patchsize = 0;
1843                }
1844                else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
1845                        for (i = 0; binhdr[i]; i++) {
1846                                int len = strlen(binhdr[i]);
1847                                if (len < size - hd &&
1848                                    !memcmp(binhdr[i], buffer + hd, len)) {
1849                                        linenr++;
1850                                        patch->is_binary = 1;
1851                                        patchsize = llen;
1852                                        break;
1853                                }
1854                        }
1855                }
1856
1857                /* Empty patch cannot be applied if it is a text patch
1858                 * without metadata change.  A binary patch appears
1859                 * empty to us here.
1860                 */
1861                if ((apply || check) &&
1862                    (!patch->is_binary && !metadata_changes(patch)))
1863                        die("patch with only garbage at line %d", linenr);
1864        }
1865
1866        return offset + hdrsize + patchsize;
1867}
1868
1869#define swap(a,b) myswap((a),(b),sizeof(a))
1870
1871#define myswap(a, b, size) do {         \
1872        unsigned char mytmp[size];      \
1873        memcpy(mytmp, &a, size);                \
1874        memcpy(&a, &b, size);           \
1875        memcpy(&b, mytmp, size);                \
1876} while (0)
1877
1878static void reverse_patches(struct patch *p)
1879{
1880        for (; p; p = p->next) {
1881                struct fragment *frag = p->fragments;
1882
1883                swap(p->new_name, p->old_name);
1884                swap(p->new_mode, p->old_mode);
1885                swap(p->is_new, p->is_delete);
1886                swap(p->lines_added, p->lines_deleted);
1887                swap(p->old_sha1_prefix, p->new_sha1_prefix);
1888
1889                for (; frag; frag = frag->next) {
1890                        swap(frag->newpos, frag->oldpos);
1891                        swap(frag->newlines, frag->oldlines);
1892                }
1893        }
1894}
1895
1896static const char pluses[] =
1897"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++";
1898static const char minuses[]=
1899"----------------------------------------------------------------------";
1900
1901static void show_stats(struct patch *patch)
1902{
1903        struct strbuf qname = STRBUF_INIT;
1904        char *cp = patch->new_name ? patch->new_name : patch->old_name;
1905        int max, add, del;
1906
1907        quote_c_style(cp, &qname, NULL, 0);
1908
1909        /*
1910         * "scale" the filename
1911         */
1912        max = max_len;
1913        if (max > 50)
1914                max = 50;
1915
1916        if (qname.len > max) {
1917                cp = strchr(qname.buf + qname.len + 3 - max, '/');
1918                if (!cp)
1919                        cp = qname.buf + qname.len + 3 - max;
1920                strbuf_splice(&qname, 0, cp - qname.buf, "...", 3);
1921        }
1922
1923        if (patch->is_binary) {
1924                printf(" %-*s |  Bin\n", max, qname.buf);
1925                strbuf_release(&qname);
1926                return;
1927        }
1928
1929        printf(" %-*s |", max, qname.buf);
1930        strbuf_release(&qname);
1931
1932        /*
1933         * scale the add/delete
1934         */
1935        max = max + max_change > 70 ? 70 - max : max_change;
1936        add = patch->lines_added;
1937        del = patch->lines_deleted;
1938
1939        if (max_change > 0) {
1940                int total = ((add + del) * max + max_change / 2) / max_change;
1941                add = (add * max + max_change / 2) / max_change;
1942                del = total - add;
1943        }
1944        printf("%5d %.*s%.*s\n", patch->lines_added + patch->lines_deleted,
1945                add, pluses, del, minuses);
1946}
1947
1948static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
1949{
1950        switch (st->st_mode & S_IFMT) {
1951        case S_IFLNK:
1952                if (strbuf_readlink(buf, path, st->st_size) < 0)
1953                        return error("unable to read symlink %s", path);
1954                return 0;
1955        case S_IFREG:
1956                if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
1957                        return error("unable to open or read %s", path);
1958                convert_to_git(path, buf->buf, buf->len, buf, 0);
1959                return 0;
1960        default:
1961                return -1;
1962        }
1963}
1964
1965/*
1966 * Update the preimage, and the common lines in postimage,
1967 * from buffer buf of length len. If postlen is 0 the postimage
1968 * is updated in place, otherwise it's updated on a new buffer
1969 * of length postlen
1970 */
1971
1972static void update_pre_post_images(struct image *preimage,
1973                                   struct image *postimage,
1974                                   char *buf,
1975                                   size_t len, size_t postlen)
1976{
1977        int i, ctx;
1978        char *new, *old, *fixed;
1979        struct image fixed_preimage;
1980
1981        /*
1982         * Update the preimage with whitespace fixes.  Note that we
1983         * are not losing preimage->buf -- apply_one_fragment() will
1984         * free "oldlines".
1985         */
1986        prepare_image(&fixed_preimage, buf, len, 1);
1987        assert(fixed_preimage.nr == preimage->nr);
1988        for (i = 0; i < preimage->nr; i++)
1989                fixed_preimage.line[i].flag = preimage->line[i].flag;
1990        free(preimage->line_allocated);
1991        *preimage = fixed_preimage;
1992
1993        /*
1994         * Adjust the common context lines in postimage. This can be
1995         * done in-place when we are just doing whitespace fixing,
1996         * which does not make the string grow, but needs a new buffer
1997         * when ignoring whitespace causes the update, since in this case
1998         * we could have e.g. tabs converted to multiple spaces.
1999         * We trust the caller to tell us if the update can be done
2000         * in place (postlen==0) or not.
2001         */
2002        old = postimage->buf;
2003        if (postlen)
2004                new = postimage->buf = xmalloc(postlen);
2005        else
2006                new = old;
2007        fixed = preimage->buf;
2008        for (i = ctx = 0; i < postimage->nr; i++) {
2009                size_t len = postimage->line[i].len;
2010                if (!(postimage->line[i].flag & LINE_COMMON)) {
2011                        /* an added line -- no counterparts in preimage */
2012                        memmove(new, old, len);
2013                        old += len;
2014                        new += len;
2015                        continue;
2016                }
2017
2018                /* a common context -- skip it in the original postimage */
2019                old += len;
2020
2021                /* and find the corresponding one in the fixed preimage */
2022                while (ctx < preimage->nr &&
2023                       !(preimage->line[ctx].flag & LINE_COMMON)) {
2024                        fixed += preimage->line[ctx].len;
2025                        ctx++;
2026                }
2027                if (preimage->nr <= ctx)
2028                        die("oops");
2029
2030                /* and copy it in, while fixing the line length */
2031                len = preimage->line[ctx].len;
2032                memcpy(new, fixed, len);
2033                new += len;
2034                fixed += len;
2035                postimage->line[i].len = len;
2036                ctx++;
2037        }
2038
2039        /* Fix the length of the whole thing */
2040        postimage->len = new - postimage->buf;
2041}
2042
2043static int match_fragment(struct image *img,
2044                          struct image *preimage,
2045                          struct image *postimage,
2046                          unsigned long try,
2047                          int try_lno,
2048                          unsigned ws_rule,
2049                          int match_beginning, int match_end)
2050{
2051        int i;
2052        char *fixed_buf, *buf, *orig, *target;
2053        struct strbuf fixed;
2054        size_t fixed_len;
2055        int preimage_limit;
2056
2057        if (preimage->nr + try_lno <= img->nr) {
2058                /*
2059                 * The hunk falls within the boundaries of img.
2060                 */
2061                preimage_limit = preimage->nr;
2062                if (match_end && (preimage->nr + try_lno != img->nr))
2063                        return 0;
2064        } else if (ws_error_action == correct_ws_error &&
2065                   (ws_rule & WS_BLANK_AT_EOF)) {
2066                /*
2067                 * This hunk extends beyond the end of img, and we are
2068                 * removing blank lines at the end of the file.  This
2069                 * many lines from the beginning of the preimage must
2070                 * match with img, and the remainder of the preimage
2071                 * must be blank.
2072                 */
2073                preimage_limit = img->nr - try_lno;
2074        } else {
2075                /*
2076                 * The hunk extends beyond the end of the img and
2077                 * we are not removing blanks at the end, so we
2078                 * should reject the hunk at this position.
2079                 */
2080                return 0;
2081        }
2082
2083        if (match_beginning && try_lno)
2084                return 0;
2085
2086        /* Quick hash check */
2087        for (i = 0; i < preimage_limit; i++)
2088                if (preimage->line[i].hash != img->line[try_lno + i].hash)
2089                        return 0;
2090
2091        if (preimage_limit == preimage->nr) {
2092                /*
2093                 * Do we have an exact match?  If we were told to match
2094                 * at the end, size must be exactly at try+fragsize,
2095                 * otherwise try+fragsize must be still within the preimage,
2096                 * and either case, the old piece should match the preimage
2097                 * exactly.
2098                 */
2099                if ((match_end
2100                     ? (try + preimage->len == img->len)
2101                     : (try + preimage->len <= img->len)) &&
2102                    !memcmp(img->buf + try, preimage->buf, preimage->len))
2103                        return 1;
2104        } else {
2105                /*
2106                 * The preimage extends beyond the end of img, so
2107                 * there cannot be an exact match.
2108                 *
2109                 * There must be one non-blank context line that match
2110                 * a line before the end of img.
2111                 */
2112                char *buf_end;
2113
2114                buf = preimage->buf;
2115                buf_end = buf;
2116                for (i = 0; i < preimage_limit; i++)
2117                        buf_end += preimage->line[i].len;
2118
2119                for ( ; buf < buf_end; buf++)
2120                        if (!isspace(*buf))
2121                                break;
2122                if (buf == buf_end)
2123                        return 0;
2124        }
2125
2126        /*
2127         * No exact match. If we are ignoring whitespace, run a line-by-line
2128         * fuzzy matching. We collect all the line length information because
2129         * we need it to adjust whitespace if we match.
2130         */
2131        if (ws_ignore_action == ignore_ws_change) {
2132                size_t imgoff = 0;
2133                size_t preoff = 0;
2134                size_t postlen = postimage->len;
2135                size_t extra_chars;
2136                char *preimage_eof;
2137                char *preimage_end;
2138                for (i = 0; i < preimage_limit; i++) {
2139                        size_t prelen = preimage->line[i].len;
2140                        size_t imglen = img->line[try_lno+i].len;
2141
2142                        if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
2143                                              preimage->buf + preoff, prelen))
2144                                return 0;
2145                        if (preimage->line[i].flag & LINE_COMMON)
2146                                postlen += imglen - prelen;
2147                        imgoff += imglen;
2148                        preoff += prelen;
2149                }
2150
2151                /*
2152                 * Ok, the preimage matches with whitespace fuzz.
2153                 *
2154                 * imgoff now holds the true length of the target that
2155                 * matches the preimage before the end of the file.
2156                 *
2157                 * Count the number of characters in the preimage that fall
2158                 * beyond the end of the file and make sure that all of them
2159                 * are whitespace characters. (This can only happen if
2160                 * we are removing blank lines at the end of the file.)
2161                 */
2162                buf = preimage_eof = preimage->buf + preoff;
2163                for ( ; i < preimage->nr; i++)
2164                        preoff += preimage->line[i].len;
2165                preimage_end = preimage->buf + preoff;
2166                for ( ; buf < preimage_end; buf++)
2167                        if (!isspace(*buf))
2168                                return 0;
2169
2170                /*
2171                 * Update the preimage and the common postimage context
2172                 * lines to use the same whitespace as the target.
2173                 * If whitespace is missing in the target (i.e.
2174                 * if the preimage extends beyond the end of the file),
2175                 * use the whitespace from the preimage.
2176                 */
2177                extra_chars = preimage_end - preimage_eof;
2178                strbuf_init(&fixed, imgoff + extra_chars);
2179                strbuf_add(&fixed, img->buf + try, imgoff);
2180                strbuf_add(&fixed, preimage_eof, extra_chars);
2181                fixed_buf = strbuf_detach(&fixed, &fixed_len);
2182                update_pre_post_images(preimage, postimage,
2183                                fixed_buf, fixed_len, postlen);
2184                return 1;
2185        }
2186
2187        if (ws_error_action != correct_ws_error)
2188                return 0;
2189
2190        /*
2191         * The hunk does not apply byte-by-byte, but the hash says
2192         * it might with whitespace fuzz. We haven't been asked to
2193         * ignore whitespace, we were asked to correct whitespace
2194         * errors, so let's try matching after whitespace correction.
2195         *
2196         * The preimage may extend beyond the end of the file,
2197         * but in this loop we will only handle the part of the
2198         * preimage that falls within the file.
2199         */
2200        strbuf_init(&fixed, preimage->len + 1);
2201        orig = preimage->buf;
2202        target = img->buf + try;
2203        for (i = 0; i < preimage_limit; i++) {
2204                size_t oldlen = preimage->line[i].len;
2205                size_t tgtlen = img->line[try_lno + i].len;
2206                size_t fixstart = fixed.len;
2207                struct strbuf tgtfix;
2208                int match;
2209
2210                /* Try fixing the line in the preimage */
2211                ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2212
2213                /* Try fixing the line in the target */
2214                strbuf_init(&tgtfix, tgtlen);
2215                ws_fix_copy(&tgtfix, target, tgtlen, ws_rule, NULL);
2216
2217                /*
2218                 * If they match, either the preimage was based on
2219                 * a version before our tree fixed whitespace breakage,
2220                 * or we are lacking a whitespace-fix patch the tree
2221                 * the preimage was based on already had (i.e. target
2222                 * has whitespace breakage, the preimage doesn't).
2223                 * In either case, we are fixing the whitespace breakages
2224                 * so we might as well take the fix together with their
2225                 * real change.
2226                 */
2227                match = (tgtfix.len == fixed.len - fixstart &&
2228                         !memcmp(tgtfix.buf, fixed.buf + fixstart,
2229                                             fixed.len - fixstart));
2230
2231                strbuf_release(&tgtfix);
2232                if (!match)
2233                        goto unmatch_exit;
2234
2235                orig += oldlen;
2236                target += tgtlen;
2237        }
2238
2239
2240        /*
2241         * Now handle the lines in the preimage that falls beyond the
2242         * end of the file (if any). They will only match if they are
2243         * empty or only contain whitespace (if WS_BLANK_AT_EOL is
2244         * false).
2245         */
2246        for ( ; i < preimage->nr; i++) {
2247                size_t fixstart = fixed.len; /* start of the fixed preimage */
2248                size_t oldlen = preimage->line[i].len;
2249                int j;
2250
2251                /* Try fixing the line in the preimage */
2252                ws_fix_copy(&fixed, orig, oldlen, ws_rule, NULL);
2253
2254                for (j = fixstart; j < fixed.len; j++)
2255                        if (!isspace(fixed.buf[j]))
2256                                goto unmatch_exit;
2257
2258                orig += oldlen;
2259        }
2260
2261        /*
2262         * Yes, the preimage is based on an older version that still
2263         * has whitespace breakages unfixed, and fixing them makes the
2264         * hunk match.  Update the context lines in the postimage.
2265         */
2266        fixed_buf = strbuf_detach(&fixed, &fixed_len);
2267        update_pre_post_images(preimage, postimage,
2268                               fixed_buf, fixed_len, 0);
2269        return 1;
2270
2271 unmatch_exit:
2272        strbuf_release(&fixed);
2273        return 0;
2274}
2275
2276static int find_pos(struct image *img,
2277                    struct image *preimage,
2278                    struct image *postimage,
2279                    int line,
2280                    unsigned ws_rule,
2281                    int match_beginning, int match_end)
2282{
2283        int i;
2284        unsigned long backwards, forwards, try;
2285        int backwards_lno, forwards_lno, try_lno;
2286
2287        /*
2288         * If match_beginning or match_end is specified, there is no
2289         * point starting from a wrong line that will never match and
2290         * wander around and wait for a match at the specified end.
2291         */
2292        if (match_beginning)
2293                line = 0;
2294        else if (match_end)
2295                line = img->nr - preimage->nr;
2296
2297        /*
2298         * Because the comparison is unsigned, the following test
2299         * will also take care of a negative line number that can
2300         * result when match_end and preimage is larger than the target.
2301         */
2302        if ((size_t) line > img->nr)
2303                line = img->nr;
2304
2305        try = 0;
2306        for (i = 0; i < line; i++)
2307                try += img->line[i].len;
2308
2309        /*
2310         * There's probably some smart way to do this, but I'll leave
2311         * that to the smart and beautiful people. I'm simple and stupid.
2312         */
2313        backwards = try;
2314        backwards_lno = line;
2315        forwards = try;
2316        forwards_lno = line;
2317        try_lno = line;
2318
2319        for (i = 0; ; i++) {
2320                if (match_fragment(img, preimage, postimage,
2321                                   try, try_lno, ws_rule,
2322                                   match_beginning, match_end))
2323                        return try_lno;
2324
2325        again:
2326                if (backwards_lno == 0 && forwards_lno == img->nr)
2327                        break;
2328
2329                if (i & 1) {
2330                        if (backwards_lno == 0) {
2331                                i++;
2332                                goto again;
2333                        }
2334                        backwards_lno--;
2335                        backwards -= img->line[backwards_lno].len;
2336                        try = backwards;
2337                        try_lno = backwards_lno;
2338                } else {
2339                        if (forwards_lno == img->nr) {
2340                                i++;
2341                                goto again;
2342                        }
2343                        forwards += img->line[forwards_lno].len;
2344                        forwards_lno++;
2345                        try = forwards;
2346                        try_lno = forwards_lno;
2347                }
2348
2349        }
2350        return -1;
2351}
2352
2353static void remove_first_line(struct image *img)
2354{
2355        img->buf += img->line[0].len;
2356        img->len -= img->line[0].len;
2357        img->line++;
2358        img->nr--;
2359}
2360
2361static void remove_last_line(struct image *img)
2362{
2363        img->len -= img->line[--img->nr].len;
2364}
2365
2366static void update_image(struct image *img,
2367                         int applied_pos,
2368                         struct image *preimage,
2369                         struct image *postimage)
2370{
2371        /*
2372         * remove the copy of preimage at offset in img
2373         * and replace it with postimage
2374         */
2375        int i, nr;
2376        size_t remove_count, insert_count, applied_at = 0;
2377        char *result;
2378        int preimage_limit;
2379
2380        /*
2381         * If we are removing blank lines at the end of img,
2382         * the preimage may extend beyond the end.
2383         * If that is the case, we must be careful only to
2384         * remove the part of the preimage that falls within
2385         * the boundaries of img. Initialize preimage_limit
2386         * to the number of lines in the preimage that falls
2387         * within the boundaries.
2388         */
2389        preimage_limit = preimage->nr;
2390        if (preimage_limit > img->nr - applied_pos)
2391                preimage_limit = img->nr - applied_pos;
2392
2393        for (i = 0; i < applied_pos; i++)
2394                applied_at += img->line[i].len;
2395
2396        remove_count = 0;
2397        for (i = 0; i < preimage_limit; i++)
2398                remove_count += img->line[applied_pos + i].len;
2399        insert_count = postimage->len;
2400
2401        /* Adjust the contents */
2402        result = xmalloc(img->len + insert_count - remove_count + 1);
2403        memcpy(result, img->buf, applied_at);
2404        memcpy(result + applied_at, postimage->buf, postimage->len);
2405        memcpy(result + applied_at + postimage->len,
2406               img->buf + (applied_at + remove_count),
2407               img->len - (applied_at + remove_count));
2408        free(img->buf);
2409        img->buf = result;
2410        img->len += insert_count - remove_count;
2411        result[img->len] = '\0';
2412
2413        /* Adjust the line table */
2414        nr = img->nr + postimage->nr - preimage_limit;
2415        if (preimage_limit < postimage->nr) {
2416                /*
2417                 * NOTE: this knows that we never call remove_first_line()
2418                 * on anything other than pre/post image.
2419                 */
2420                img->line = xrealloc(img->line, nr * sizeof(*img->line));
2421                img->line_allocated = img->line;
2422        }
2423        if (preimage_limit != postimage->nr)
2424                memmove(img->line + applied_pos + postimage->nr,
2425                        img->line + applied_pos + preimage_limit,
2426                        (img->nr - (applied_pos + preimage_limit)) *
2427                        sizeof(*img->line));
2428        memcpy(img->line + applied_pos,
2429               postimage->line,
2430               postimage->nr * sizeof(*img->line));
2431        img->nr = nr;
2432}
2433
2434static int apply_one_fragment(struct image *img, struct fragment *frag,
2435                              int inaccurate_eof, unsigned ws_rule)
2436{
2437        int match_beginning, match_end;
2438        const char *patch = frag->patch;
2439        int size = frag->size;
2440        char *old, *oldlines;
2441        struct strbuf newlines;
2442        int new_blank_lines_at_end = 0;
2443        unsigned long leading, trailing;
2444        int pos, applied_pos;
2445        struct image preimage;
2446        struct image postimage;
2447
2448        memset(&preimage, 0, sizeof(preimage));
2449        memset(&postimage, 0, sizeof(postimage));
2450        oldlines = xmalloc(size);
2451        strbuf_init(&newlines, size);
2452
2453        old = oldlines;
2454        while (size > 0) {
2455                char first;
2456                int len = linelen(patch, size);
2457                int plen;
2458                int added_blank_line = 0;
2459                int is_blank_context = 0;
2460                size_t start;
2461
2462                if (!len)
2463                        break;
2464
2465                /*
2466                 * "plen" is how much of the line we should use for
2467                 * the actual patch data. Normally we just remove the
2468                 * first character on the line, but if the line is
2469                 * followed by "\ No newline", then we also remove the
2470                 * last one (which is the newline, of course).
2471                 */
2472                plen = len - 1;
2473                if (len < size && patch[len] == '\\')
2474                        plen--;
2475                first = *patch;
2476                if (apply_in_reverse) {
2477                        if (first == '-')
2478                                first = '+';
2479                        else if (first == '+')
2480                                first = '-';
2481                }
2482
2483                switch (first) {
2484                case '\n':
2485                        /* Newer GNU diff, empty context line */
2486                        if (plen < 0)
2487                                /* ... followed by '\No newline'; nothing */
2488                                break;
2489                        *old++ = '\n';
2490                        strbuf_addch(&newlines, '\n');
2491                        add_line_info(&preimage, "\n", 1, LINE_COMMON);
2492                        add_line_info(&postimage, "\n", 1, LINE_COMMON);
2493                        is_blank_context = 1;
2494                        break;
2495                case ' ':
2496                        if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
2497                            ws_blank_line(patch + 1, plen, ws_rule))
2498                                is_blank_context = 1;
2499                case '-':
2500                        memcpy(old, patch + 1, plen);
2501                        add_line_info(&preimage, old, plen,
2502                                      (first == ' ' ? LINE_COMMON : 0));
2503                        old += plen;
2504                        if (first == '-')
2505                                break;
2506                /* Fall-through for ' ' */
2507                case '+':
2508                        /* --no-add does not add new lines */
2509                        if (first == '+' && no_add)
2510                                break;
2511
2512                        start = newlines.len;
2513                        if (first != '+' ||
2514                            !whitespace_error ||
2515                            ws_error_action != correct_ws_error) {
2516                                strbuf_add(&newlines, patch + 1, plen);
2517                        }
2518                        else {
2519                                ws_fix_copy(&newlines, patch + 1, plen, ws_rule, &applied_after_fixing_ws);
2520                        }
2521                        add_line_info(&postimage, newlines.buf + start, newlines.len - start,
2522                                      (first == '+' ? 0 : LINE_COMMON));
2523                        if (first == '+' &&
2524                            (ws_rule & WS_BLANK_AT_EOF) &&
2525                            ws_blank_line(patch + 1, plen, ws_rule))
2526                                added_blank_line = 1;
2527                        break;
2528                case '@': case '\\':
2529                        /* Ignore it, we already handled it */
2530                        break;
2531                default:
2532                        if (apply_verbosely)
2533                                error("invalid start of line: '%c'", first);
2534                        return -1;
2535                }
2536                if (added_blank_line)
2537                        new_blank_lines_at_end++;
2538                else if (is_blank_context)
2539                        ;
2540                else
2541                        new_blank_lines_at_end = 0;
2542                patch += len;
2543                size -= len;
2544        }
2545        if (inaccurate_eof &&
2546            old > oldlines && old[-1] == '\n' &&
2547            newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
2548                old--;
2549                strbuf_setlen(&newlines, newlines.len - 1);
2550        }
2551
2552        leading = frag->leading;
2553        trailing = frag->trailing;
2554
2555        /*
2556         * A hunk to change lines at the beginning would begin with
2557         * @@ -1,L +N,M @@
2558         * but we need to be careful.  -U0 that inserts before the second
2559         * line also has this pattern.
2560         *
2561         * And a hunk to add to an empty file would begin with
2562         * @@ -0,0 +N,M @@
2563         *
2564         * In other words, a hunk that is (frag->oldpos <= 1) with or
2565         * without leading context must match at the beginning.
2566         */
2567        match_beginning = (!frag->oldpos ||
2568                           (frag->oldpos == 1 && !unidiff_zero));
2569
2570        /*
2571         * A hunk without trailing lines must match at the end.
2572         * However, we simply cannot tell if a hunk must match end
2573         * from the lack of trailing lines if the patch was generated
2574         * with unidiff without any context.
2575         */
2576        match_end = !unidiff_zero && !trailing;
2577
2578        pos = frag->newpos ? (frag->newpos - 1) : 0;
2579        preimage.buf = oldlines;
2580        preimage.len = old - oldlines;
2581        postimage.buf = newlines.buf;
2582        postimage.len = newlines.len;
2583        preimage.line = preimage.line_allocated;
2584        postimage.line = postimage.line_allocated;
2585
2586        for (;;) {
2587
2588                applied_pos = find_pos(img, &preimage, &postimage, pos,
2589                                       ws_rule, match_beginning, match_end);
2590
2591                if (applied_pos >= 0)
2592                        break;
2593
2594                /* Am I at my context limits? */
2595                if ((leading <= p_context) && (trailing <= p_context))
2596                        break;
2597                if (match_beginning || match_end) {
2598                        match_beginning = match_end = 0;
2599                        continue;
2600                }
2601
2602                /*
2603                 * Reduce the number of context lines; reduce both
2604                 * leading and trailing if they are equal otherwise
2605                 * just reduce the larger context.
2606                 */
2607                if (leading >= trailing) {
2608                        remove_first_line(&preimage);
2609                        remove_first_line(&postimage);
2610                        pos--;
2611                        leading--;
2612                }
2613                if (trailing > leading) {
2614                        remove_last_line(&preimage);
2615                        remove_last_line(&postimage);
2616                        trailing--;
2617                }
2618        }
2619
2620        if (applied_pos >= 0) {
2621                if (new_blank_lines_at_end &&
2622                    preimage.nr + applied_pos >= img->nr &&
2623                    (ws_rule & WS_BLANK_AT_EOF) &&
2624                    ws_error_action != nowarn_ws_error) {
2625                        record_ws_error(WS_BLANK_AT_EOF, "+", 1, frag->linenr);
2626                        if (ws_error_action == correct_ws_error) {
2627                                while (new_blank_lines_at_end--)
2628                                        remove_last_line(&postimage);
2629                        }
2630                        /*
2631                         * We would want to prevent write_out_results()
2632                         * from taking place in apply_patch() that follows
2633                         * the callchain led us here, which is:
2634                         * apply_patch->check_patch_list->check_patch->
2635                         * apply_data->apply_fragments->apply_one_fragment
2636                         */
2637                        if (ws_error_action == die_on_ws_error)
2638                                apply = 0;
2639                }
2640
2641                /*
2642                 * Warn if it was necessary to reduce the number
2643                 * of context lines.
2644                 */
2645                if ((leading != frag->leading) ||
2646                    (trailing != frag->trailing))
2647                        fprintf(stderr, "Context reduced to (%ld/%ld)"
2648                                " to apply fragment at %d\n",
2649                                leading, trailing, applied_pos+1);
2650                update_image(img, applied_pos, &preimage, &postimage);
2651        } else {
2652                if (apply_verbosely)
2653                        error("while searching for:\n%.*s",
2654                              (int)(old - oldlines), oldlines);
2655        }
2656
2657        free(oldlines);
2658        strbuf_release(&newlines);
2659        free(preimage.line_allocated);
2660        free(postimage.line_allocated);
2661
2662        return (applied_pos < 0);
2663}
2664
2665static int apply_binary_fragment(struct image *img, struct patch *patch)
2666{
2667        struct fragment *fragment = patch->fragments;
2668        unsigned long len;
2669        void *dst;
2670
2671        if (!fragment)
2672                return error("missing binary patch data for '%s'",
2673                             patch->new_name ?
2674                             patch->new_name :
2675                             patch->old_name);
2676
2677        /* Binary patch is irreversible without the optional second hunk */
2678        if (apply_in_reverse) {
2679                if (!fragment->next)
2680                        return error("cannot reverse-apply a binary patch "
2681                                     "without the reverse hunk to '%s'",
2682                                     patch->new_name
2683                                     ? patch->new_name : patch->old_name);
2684                fragment = fragment->next;
2685        }
2686        switch (fragment->binary_patch_method) {
2687        case BINARY_DELTA_DEFLATED:
2688                dst = patch_delta(img->buf, img->len, fragment->patch,
2689                                  fragment->size, &len);
2690                if (!dst)
2691                        return -1;
2692                clear_image(img);
2693                img->buf = dst;
2694                img->len = len;
2695                return 0;
2696        case BINARY_LITERAL_DEFLATED:
2697                clear_image(img);
2698                img->len = fragment->size;
2699                img->buf = xmalloc(img->len+1);
2700                memcpy(img->buf, fragment->patch, img->len);
2701                img->buf[img->len] = '\0';
2702                return 0;
2703        }
2704        return -1;
2705}
2706
2707static int apply_binary(struct image *img, struct patch *patch)
2708{
2709        const char *name = patch->old_name ? patch->old_name : patch->new_name;
2710        unsigned char sha1[20];
2711
2712        /*
2713         * For safety, we require patch index line to contain
2714         * full 40-byte textual SHA1 for old and new, at least for now.
2715         */
2716        if (strlen(patch->old_sha1_prefix) != 40 ||
2717            strlen(patch->new_sha1_prefix) != 40 ||
2718            get_sha1_hex(patch->old_sha1_prefix, sha1) ||
2719            get_sha1_hex(patch->new_sha1_prefix, sha1))
2720                return error("cannot apply binary patch to '%s' "
2721                             "without full index line", name);
2722
2723        if (patch->old_name) {
2724                /*
2725                 * See if the old one matches what the patch
2726                 * applies to.
2727                 */
2728                hash_sha1_file(img->buf, img->len, blob_type, sha1);
2729                if (strcmp(sha1_to_hex(sha1), patch->old_sha1_prefix))
2730                        return error("the patch applies to '%s' (%s), "
2731                                     "which does not match the "
2732                                     "current contents.",
2733                                     name, sha1_to_hex(sha1));
2734        }
2735        else {
2736                /* Otherwise, the old one must be empty. */
2737                if (img->len)
2738                        return error("the patch applies to an empty "
2739                                     "'%s' but it is not empty", name);
2740        }
2741
2742        get_sha1_hex(patch->new_sha1_prefix, sha1);
2743        if (is_null_sha1(sha1)) {
2744                clear_image(img);
2745                return 0; /* deletion patch */
2746        }
2747
2748        if (has_sha1_file(sha1)) {
2749                /* We already have the postimage */
2750                enum object_type type;
2751                unsigned long size;
2752                char *result;
2753
2754                result = read_sha1_file(sha1, &type, &size);
2755                if (!result)
2756                        return error("the necessary postimage %s for "
2757                                     "'%s' cannot be read",
2758                                     patch->new_sha1_prefix, name);
2759                clear_image(img);
2760                img->buf = result;
2761                img->len = size;
2762        } else {
2763                /*
2764                 * We have verified buf matches the preimage;
2765                 * apply the patch data to it, which is stored
2766                 * in the patch->fragments->{patch,size}.
2767                 */
2768                if (apply_binary_fragment(img, patch))
2769                        return error("binary patch does not apply to '%s'",
2770                                     name);
2771
2772                /* verify that the result matches */
2773                hash_sha1_file(img->buf, img->len, blob_type, sha1);
2774                if (strcmp(sha1_to_hex(sha1), patch->new_sha1_prefix))
2775                        return error("binary patch to '%s' creates incorrect result (expecting %s, got %s)",
2776                                name, patch->new_sha1_prefix, sha1_to_hex(sha1));
2777        }
2778
2779        return 0;
2780}
2781
2782static int apply_fragments(struct image *img, struct patch *patch)
2783{
2784        struct fragment *frag = patch->fragments;
2785        const char *name = patch->old_name ? patch->old_name : patch->new_name;
2786        unsigned ws_rule = patch->ws_rule;
2787        unsigned inaccurate_eof = patch->inaccurate_eof;
2788
2789        if (patch->is_binary)
2790                return apply_binary(img, patch);
2791
2792        while (frag) {
2793                if (apply_one_fragment(img, frag, inaccurate_eof, ws_rule)) {
2794                        error("patch failed: %s:%ld", name, frag->oldpos);
2795                        if (!apply_with_reject)
2796                                return -1;
2797                        frag->rejected = 1;
2798                }
2799                frag = frag->next;
2800        }
2801        return 0;
2802}
2803
2804static int read_file_or_gitlink(struct cache_entry *ce, struct strbuf *buf)
2805{
2806        if (!ce)
2807                return 0;
2808
2809        if (S_ISGITLINK(ce->ce_mode)) {
2810                strbuf_grow(buf, 100);
2811                strbuf_addf(buf, "Subproject commit %s\n", sha1_to_hex(ce->sha1));
2812        } else {
2813                enum object_type type;
2814                unsigned long sz;
2815                char *result;
2816
2817                result = read_sha1_file(ce->sha1, &type, &sz);
2818                if (!result)
2819                        return -1;
2820                /* XXX read_sha1_file NUL-terminates */
2821                strbuf_attach(buf, result, sz, sz + 1);
2822        }
2823        return 0;
2824}
2825
2826static struct patch *in_fn_table(const char *name)
2827{
2828        struct string_list_item *item;
2829
2830        if (name == NULL)
2831                return NULL;
2832
2833        item = string_list_lookup(&fn_table, name);
2834        if (item != NULL)
2835                return (struct patch *)item->util;
2836
2837        return NULL;
2838}
2839
2840/*
2841 * item->util in the filename table records the status of the path.
2842 * Usually it points at a patch (whose result records the contents
2843 * of it after applying it), but it could be PATH_WAS_DELETED for a
2844 * path that a previously applied patch has already removed.
2845 */
2846 #define PATH_TO_BE_DELETED ((struct patch *) -2)
2847#define PATH_WAS_DELETED ((struct patch *) -1)
2848
2849static int to_be_deleted(struct patch *patch)
2850{
2851        return patch == PATH_TO_BE_DELETED;
2852}
2853
2854static int was_deleted(struct patch *patch)
2855{
2856        return patch == PATH_WAS_DELETED;
2857}
2858
2859static void add_to_fn_table(struct patch *patch)
2860{
2861        struct string_list_item *item;
2862
2863        /*
2864         * Always add new_name unless patch is a deletion
2865         * This should cover the cases for normal diffs,
2866         * file creations and copies
2867         */
2868        if (patch->new_name != NULL) {
2869                item = string_list_insert(&fn_table, patch->new_name);
2870                item->util = patch;
2871        }
2872
2873        /*
2874         * store a failure on rename/deletion cases because
2875         * later chunks shouldn't patch old names
2876         */
2877        if ((patch->new_name == NULL) || (patch->is_rename)) {
2878                item = string_list_insert(&fn_table, patch->old_name);
2879                item->util = PATH_WAS_DELETED;
2880        }
2881}
2882
2883static void prepare_fn_table(struct patch *patch)
2884{
2885        /*
2886         * store information about incoming file deletion
2887         */
2888        while (patch) {
2889                if ((patch->new_name == NULL) || (patch->is_rename)) {
2890                        struct string_list_item *item;
2891                        item = string_list_insert(&fn_table, patch->old_name);
2892                        item->util = PATH_TO_BE_DELETED;
2893                }
2894                patch = patch->next;
2895        }
2896}
2897
2898static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce)
2899{
2900        struct strbuf buf = STRBUF_INIT;
2901        struct image image;
2902        size_t len;
2903        char *img;
2904        struct patch *tpatch;
2905
2906        if (!(patch->is_copy || patch->is_rename) &&
2907            (tpatch = in_fn_table(patch->old_name)) != NULL && !to_be_deleted(tpatch)) {
2908                if (was_deleted(tpatch)) {
2909                        return error("patch %s has been renamed/deleted",
2910                                patch->old_name);
2911                }
2912                /* We have a patched copy in memory use that */
2913                strbuf_add(&buf, tpatch->result, tpatch->resultsize);
2914        } else if (cached) {
2915                if (read_file_or_gitlink(ce, &buf))
2916                        return error("read of %s failed", patch->old_name);
2917        } else if (patch->old_name) {
2918                if (S_ISGITLINK(patch->old_mode)) {
2919                        if (ce) {
2920                                read_file_or_gitlink(ce, &buf);
2921                        } else {
2922                                /*
2923                                 * There is no way to apply subproject
2924                                 * patch without looking at the index.
2925                                 */
2926                                patch->fragments = NULL;
2927                        }
2928                } else {
2929                        if (read_old_data(st, patch->old_name, &buf))
2930                                return error("read of %s failed", patch->old_name);
2931                }
2932        }
2933
2934        img = strbuf_detach(&buf, &len);
2935        prepare_image(&image, img, len, !patch->is_binary);
2936
2937        if (apply_fragments(&image, patch) < 0)
2938                return -1; /* note with --reject this succeeds. */
2939        patch->result = image.buf;
2940        patch->resultsize = image.len;
2941        add_to_fn_table(patch);
2942        free(image.line_allocated);
2943
2944        if (0 < patch->is_delete && patch->resultsize)
2945                return error("removal patch leaves file contents");
2946
2947        return 0;
2948}
2949
2950static int check_to_create_blob(const char *new_name, int ok_if_exists)
2951{
2952        struct stat nst;
2953        if (!lstat(new_name, &nst)) {
2954                if (S_ISDIR(nst.st_mode) || ok_if_exists)
2955                        return 0;
2956                /*
2957                 * A leading component of new_name might be a symlink
2958                 * that is going to be removed with this patch, but
2959                 * still pointing at somewhere that has the path.
2960                 * In such a case, path "new_name" does not exist as
2961                 * far as git is concerned.
2962                 */
2963                if (has_symlink_leading_path(new_name, strlen(new_name)))
2964                        return 0;
2965
2966                return error("%s: already exists in working directory", new_name);
2967        }
2968        else if ((errno != ENOENT) && (errno != ENOTDIR))
2969                return error("%s: %s", new_name, strerror(errno));
2970        return 0;
2971}
2972
2973static int verify_index_match(struct cache_entry *ce, struct stat *st)
2974{
2975        if (S_ISGITLINK(ce->ce_mode)) {
2976                if (!S_ISDIR(st->st_mode))
2977                        return -1;
2978                return 0;
2979        }
2980        return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
2981}
2982
2983static int check_preimage(struct patch *patch, struct cache_entry **ce, struct stat *st)
2984{
2985        const char *old_name = patch->old_name;
2986        struct patch *tpatch = NULL;
2987        int stat_ret = 0;
2988        unsigned st_mode = 0;
2989
2990        /*
2991         * Make sure that we do not have local modifications from the
2992         * index when we are looking at the index.  Also make sure
2993         * we have the preimage file to be patched in the work tree,
2994         * unless --cached, which tells git to apply only in the index.
2995         */
2996        if (!old_name)
2997                return 0;
2998
2999        assert(patch->is_new <= 0);
3000
3001        if (!(patch->is_copy || patch->is_rename) &&
3002            (tpatch = in_fn_table(old_name)) != NULL && !to_be_deleted(tpatch)) {
3003                if (was_deleted(tpatch))
3004                        return error("%s: has been deleted/renamed", old_name);
3005                st_mode = tpatch->new_mode;
3006        } else if (!cached) {
3007                stat_ret = lstat(old_name, st);
3008                if (stat_ret && errno != ENOENT)
3009                        return error("%s: %s", old_name, strerror(errno));
3010        }
3011
3012        if (to_be_deleted(tpatch))
3013                tpatch = NULL;
3014
3015        if (check_index && !tpatch) {
3016                int pos = cache_name_pos(old_name, strlen(old_name));
3017                if (pos < 0) {
3018                        if (patch->is_new < 0)
3019                                goto is_new;
3020                        return error("%s: does not exist in index", old_name);
3021                }
3022                *ce = active_cache[pos];
3023                if (stat_ret < 0) {
3024                        struct checkout costate;
3025                        /* checkout */
3026                        memset(&costate, 0, sizeof(costate));
3027                        costate.base_dir = "";
3028                        costate.refresh_cache = 1;
3029                        if (checkout_entry(*ce, &costate, NULL) ||
3030                            lstat(old_name, st))
3031                                return -1;
3032                }
3033                if (!cached && verify_index_match(*ce, st))
3034                        return error("%s: does not match index", old_name);
3035                if (cached)
3036                        st_mode = (*ce)->ce_mode;
3037        } else if (stat_ret < 0) {
3038                if (patch->is_new < 0)
3039                        goto is_new;
3040                return error("%s: %s", old_name, strerror(errno));
3041        }
3042
3043        if (!cached && !tpatch)
3044                st_mode = ce_mode_from_stat(*ce, st->st_mode);
3045
3046        if (patch->is_new < 0)
3047                patch->is_new = 0;
3048        if (!patch->old_mode)
3049                patch->old_mode = st_mode;
3050        if ((st_mode ^ patch->old_mode) & S_IFMT)
3051                return error("%s: wrong type", old_name);
3052        if (st_mode != patch->old_mode)
3053                warning("%s has type %o, expected %o",
3054                        old_name, st_mode, patch->old_mode);
3055        if (!patch->new_mode && !patch->is_delete)
3056                patch->new_mode = st_mode;
3057        return 0;
3058
3059 is_new:
3060        patch->is_new = 1;
3061        patch->is_delete = 0;
3062        patch->old_name = NULL;
3063        return 0;
3064}
3065
3066static int check_patch(struct patch *patch)
3067{
3068        struct stat st;
3069        const char *old_name = patch->old_name;
3070        const char *new_name = patch->new_name;
3071        const char *name = old_name ? old_name : new_name;
3072        struct cache_entry *ce = NULL;
3073        struct patch *tpatch;
3074        int ok_if_exists;
3075        int status;
3076
3077        patch->rejected = 1; /* we will drop this after we succeed */
3078
3079        status = check_preimage(patch, &ce, &st);
3080        if (status)
3081                return status;
3082        old_name = patch->old_name;
3083
3084        if ((tpatch = in_fn_table(new_name)) &&
3085                        (was_deleted(tpatch) || to_be_deleted(tpatch)))
3086                /*
3087                 * A type-change diff is always split into a patch to
3088                 * delete old, immediately followed by a patch to
3089                 * create new (see diff.c::run_diff()); in such a case
3090                 * it is Ok that the entry to be deleted by the
3091                 * previous patch is still in the working tree and in
3092                 * the index.
3093                 */
3094                ok_if_exists = 1;
3095        else
3096                ok_if_exists = 0;
3097
3098        if (new_name &&
3099            ((0 < patch->is_new) | (0 < patch->is_rename) | patch->is_copy)) {
3100                if (check_index &&
3101                    cache_name_pos(new_name, strlen(new_name)) >= 0 &&
3102                    !ok_if_exists)
3103                        return error("%s: already exists in index", new_name);
3104                if (!cached) {
3105                        int err = check_to_create_blob(new_name, ok_if_exists);
3106                        if (err)
3107                                return err;
3108                }
3109                if (!patch->new_mode) {
3110                        if (0 < patch->is_new)
3111                                patch->new_mode = S_IFREG | 0644;
3112                        else
3113                                patch->new_mode = patch->old_mode;
3114                }
3115        }
3116
3117        if (new_name && old_name) {
3118                int same = !strcmp(old_name, new_name);
3119                if (!patch->new_mode)
3120                        patch->new_mode = patch->old_mode;
3121                if ((patch->old_mode ^ patch->new_mode) & S_IFMT)
3122                        return error("new mode (%o) of %s does not match old mode (%o)%s%s",
3123                                patch->new_mode, new_name, patch->old_mode,
3124                                same ? "" : " of ", same ? "" : old_name);
3125        }
3126
3127        if (apply_data(patch, &st, ce) < 0)
3128                return error("%s: patch does not apply", name);
3129        patch->rejected = 0;
3130        return 0;
3131}
3132
3133static int check_patch_list(struct patch *patch)
3134{
3135        int err = 0;
3136
3137        prepare_fn_table(patch);
3138        while (patch) {
3139                if (apply_verbosely)
3140                        say_patch_name(stderr,
3141                                       "Checking patch ", patch, "...\n");
3142                err |= check_patch(patch);
3143                patch = patch->next;
3144        }
3145        return err;
3146}
3147
3148/* This function tries to read the sha1 from the current index */
3149static int get_current_sha1(const char *path, unsigned char *sha1)
3150{
3151        int pos;
3152
3153        if (read_cache() < 0)
3154                return -1;
3155        pos = cache_name_pos(path, strlen(path));
3156        if (pos < 0)
3157                return -1;
3158        hashcpy(sha1, active_cache[pos]->sha1);
3159        return 0;
3160}
3161
3162/* Build an index that contains the just the files needed for a 3way merge */
3163static void build_fake_ancestor(struct patch *list, const char *filename)
3164{
3165        struct patch *patch;
3166        struct index_state result = { NULL };
3167        int fd;
3168
3169        /* Once we start supporting the reverse patch, it may be
3170         * worth showing the new sha1 prefix, but until then...
3171         */
3172        for (patch = list; patch; patch = patch->next) {
3173                const unsigned char *sha1_ptr;
3174                unsigned char sha1[20];
3175                struct cache_entry *ce;
3176                const char *name;
3177
3178                name = patch->old_name ? patch->old_name : patch->new_name;
3179                if (0 < patch->is_new)
3180                        continue;
3181                else if (get_sha1(patch->old_sha1_prefix, sha1))
3182                        /* git diff has no index line for mode/type changes */
3183                        if (!patch->lines_added && !patch->lines_deleted) {
3184                                if (get_current_sha1(patch->old_name, sha1))
3185                                        die("mode change for %s, which is not "
3186                                                "in current HEAD", name);
3187                                sha1_ptr = sha1;
3188                        } else
3189                                die("sha1 information is lacking or useless "
3190                                        "(%s).", name);
3191                else
3192                        sha1_ptr = sha1;
3193
3194                ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0);
3195                if (!ce)
3196                        die("make_cache_entry failed for path '%s'", name);
3197                if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD))
3198                        die ("Could not add %s to temporary index", name);
3199        }
3200
3201        fd = open(filename, O_WRONLY | O_CREAT, 0666);
3202        if (fd < 0 || write_index(&result, fd) || close(fd))
3203                die ("Could not write temporary index to %s", filename);
3204
3205        discard_index(&result);
3206}
3207
3208static void stat_patch_list(struct patch *patch)
3209{
3210        int files, adds, dels;
3211
3212        for (files = adds = dels = 0 ; patch ; patch = patch->next) {
3213                files++;
3214                adds += patch->lines_added;
3215                dels += patch->lines_deleted;
3216                show_stats(patch);
3217        }
3218
3219        printf(" %d files changed, %d insertions(+), %d deletions(-)\n", files, adds, dels);
3220}
3221
3222static void numstat_patch_list(struct patch *patch)
3223{
3224        for ( ; patch; patch = patch->next) {
3225                const char *name;
3226                name = patch->new_name ? patch->new_name : patch->old_name;
3227                if (patch->is_binary)
3228                        printf("-\t-\t");
3229                else
3230                        printf("%d\t%d\t", patch->lines_added, patch->lines_deleted);
3231                write_name_quoted(name, stdout, line_termination);
3232        }
3233}
3234
3235static void show_file_mode_name(const char *newdelete, unsigned int mode, const char *name)
3236{
3237        if (mode)
3238                printf(" %s mode %06o %s\n", newdelete, mode, name);
3239        else
3240                printf(" %s %s\n", newdelete, name);
3241}
3242
3243static void show_mode_change(struct patch *p, int show_name)
3244{
3245        if (p->old_mode && p->new_mode && p->old_mode != p->new_mode) {
3246                if (show_name)
3247                        printf(" mode change %06o => %06o %s\n",
3248                               p->old_mode, p->new_mode, p->new_name);
3249                else
3250                        printf(" mode change %06o => %06o\n",
3251                               p->old_mode, p->new_mode);
3252        }
3253}
3254
3255static void show_rename_copy(struct patch *p)
3256{
3257        const char *renamecopy = p->is_rename ? "rename" : "copy";
3258        const char *old, *new;
3259
3260        /* Find common prefix */
3261        old = p->old_name;
3262        new = p->new_name;
3263        while (1) {
3264                const char *slash_old, *slash_new;
3265                slash_old = strchr(old, '/');
3266                slash_new = strchr(new, '/');
3267                if (!slash_old ||
3268                    !slash_new ||
3269                    slash_old - old != slash_new - new ||
3270                    memcmp(old, new, slash_new - new))
3271                        break;
3272                old = slash_old + 1;
3273                new = slash_new + 1;
3274        }
3275        /* p->old_name thru old is the common prefix, and old and new
3276         * through the end of names are renames
3277         */
3278        if (old != p->old_name)
3279                printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
3280                       (int)(old - p->old_name), p->old_name,
3281                       old, new, p->score);
3282        else
3283                printf(" %s %s => %s (%d%%)\n", renamecopy,
3284                       p->old_name, p->new_name, p->score);
3285        show_mode_change(p, 0);
3286}
3287
3288static void summary_patch_list(struct patch *patch)
3289{
3290        struct patch *p;
3291
3292        for (p = patch; p; p = p->next) {
3293                if (p->is_new)
3294                        show_file_mode_name("create", p->new_mode, p->new_name);
3295                else if (p->is_delete)
3296                        show_file_mode_name("delete", p->old_mode, p->old_name);
3297                else {
3298                        if (p->is_rename || p->is_copy)
3299                                show_rename_copy(p);
3300                        else {
3301                                if (p->score) {
3302                                        printf(" rewrite %s (%d%%)\n",
3303                                               p->new_name, p->score);
3304                                        show_mode_change(p, 0);
3305                                }
3306                                else
3307                                        show_mode_change(p, 1);
3308                        }
3309                }
3310        }
3311}
3312
3313static void patch_stats(struct patch *patch)
3314{
3315        int lines = patch->lines_added + patch->lines_deleted;
3316
3317        if (lines > max_change)
3318                max_change = lines;
3319        if (patch->old_name) {
3320                int len = quote_c_style(patch->old_name, NULL, NULL, 0);
3321                if (!len)
3322                        len = strlen(patch->old_name);
3323                if (len > max_len)
3324                        max_len = len;
3325        }
3326        if (patch->new_name) {
3327                int len = quote_c_style(patch->new_name, NULL, NULL, 0);
3328                if (!len)
3329                        len = strlen(patch->new_name);
3330                if (len > max_len)
3331                        max_len = len;
3332        }
3333}
3334
3335static void remove_file(struct patch *patch, int rmdir_empty)
3336{
3337        if (update_index) {
3338                if (remove_file_from_cache(patch->old_name) < 0)
3339                        die("unable to remove %s from index", patch->old_name);
3340        }
3341        if (!cached) {
3342                if (!remove_or_warn(patch->old_mode, patch->old_name) && rmdir_empty) {
3343                        remove_path(patch->old_name);
3344                }
3345        }
3346}
3347
3348static void add_index_file(const char *path, unsigned mode, void *buf, unsigned long size)
3349{
3350        struct stat st;
3351        struct cache_entry *ce;
3352        int namelen = strlen(path);
3353        unsigned ce_size = cache_entry_size(namelen);
3354
3355        if (!update_index)
3356                return;
3357
3358        ce = xcalloc(1, ce_size);
3359        memcpy(ce->name, path, namelen);
3360        ce->ce_mode = create_ce_mode(mode);
3361        ce->ce_flags = namelen;
3362        if (S_ISGITLINK(mode)) {
3363                const char *s = buf;
3364
3365                if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
3366                        die("corrupt patch for subproject %s", path);
3367        } else {
3368                if (!cached) {
3369                        if (lstat(path, &st) < 0)
3370                                die_errno("unable to stat newly created file '%s'",
3371                                          path);
3372                        fill_stat_cache_info(ce, &st);
3373                }
3374                if (write_sha1_file(buf, size, blob_type, ce->sha1) < 0)
3375                        die("unable to create backing store for newly created file %s", path);
3376        }
3377        if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0)
3378                die("unable to add cache entry for %s", path);
3379}
3380
3381static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
3382{
3383        int fd;
3384        struct strbuf nbuf = STRBUF_INIT;
3385
3386        if (S_ISGITLINK(mode)) {
3387                struct stat st;
3388                if (!lstat(path, &st) && S_ISDIR(st.st_mode))
3389                        return 0;
3390                return mkdir(path, 0777);
3391        }
3392
3393        if (has_symlinks && S_ISLNK(mode))
3394                /* Although buf:size is counted string, it also is NUL
3395                 * terminated.
3396                 */
3397                return symlink(buf, path);
3398
3399        fd = open(path, O_CREAT | O_EXCL | O_WRONLY, (mode & 0100) ? 0777 : 0666);
3400        if (fd < 0)
3401                return -1;
3402
3403        if (convert_to_working_tree(path, buf, size, &nbuf)) {
3404                size = nbuf.len;
3405                buf  = nbuf.buf;
3406        }
3407        write_or_die(fd, buf, size);
3408        strbuf_release(&nbuf);
3409
3410        if (close(fd) < 0)
3411                die_errno("closing file '%s'", path);
3412        return 0;
3413}
3414
3415/*
3416 * We optimistically assume that the directories exist,
3417 * which is true 99% of the time anyway. If they don't,
3418 * we create them and try again.
3419 */
3420static void create_one_file(char *path, unsigned mode, const char *buf, unsigned long size)
3421{
3422        if (cached)
3423                return;
3424        if (!try_create_file(path, mode, buf, size))
3425                return;
3426
3427        if (errno == ENOENT) {
3428                if (safe_create_leading_directories(path))
3429                        return;
3430                if (!try_create_file(path, mode, buf, size))
3431                        return;
3432        }
3433
3434        if (errno == EEXIST || errno == EACCES) {
3435                /* We may be trying to create a file where a directory
3436                 * used to be.
3437                 */
3438                struct stat st;
3439                if (!lstat(path, &st) && (!S_ISDIR(st.st_mode) || !rmdir(path)))
3440                        errno = EEXIST;
3441        }
3442
3443        if (errno == EEXIST) {
3444                unsigned int nr = getpid();
3445
3446                for (;;) {
3447                        char newpath[PATH_MAX];
3448                        mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
3449                        if (!try_create_file(newpath, mode, buf, size)) {
3450                                if (!rename(newpath, path))
3451                                        return;
3452                                unlink_or_warn(newpath);
3453                                break;
3454                        }
3455                        if (errno != EEXIST)
3456                                break;
3457                        ++nr;
3458                }
3459        }
3460        die_errno("unable to write file '%s' mode %o", path, mode);
3461}
3462
3463static void create_file(struct patch *patch)
3464{
3465        char *path = patch->new_name;
3466        unsigned mode = patch->new_mode;
3467        unsigned long size = patch->resultsize;
3468        char *buf = patch->result;
3469
3470        if (!mode)
3471                mode = S_IFREG | 0644;
3472        create_one_file(path, mode, buf, size);
3473        add_index_file(path, mode, buf, size);
3474}
3475
3476/* phase zero is to remove, phase one is to create */
3477static void write_out_one_result(struct patch *patch, int phase)
3478{
3479        if (patch->is_delete > 0) {
3480                if (phase == 0)
3481                        remove_file(patch, 1);
3482                return;
3483        }
3484        if (patch->is_new > 0 || patch->is_copy) {
3485                if (phase == 1)
3486                        create_file(patch);
3487                return;
3488        }
3489        /*
3490         * Rename or modification boils down to the same
3491         * thing: remove the old, write the new
3492         */
3493        if (phase == 0)
3494                remove_file(patch, patch->is_rename);
3495        if (phase == 1)
3496                create_file(patch);
3497}
3498
3499static int write_out_one_reject(struct patch *patch)
3500{
3501        FILE *rej;
3502        char namebuf[PATH_MAX];
3503        struct fragment *frag;
3504        int cnt = 0;
3505
3506        for (cnt = 0, frag = patch->fragments; frag; frag = frag->next) {
3507                if (!frag->rejected)
3508                        continue;
3509                cnt++;
3510        }
3511
3512        if (!cnt) {
3513                if (apply_verbosely)
3514                        say_patch_name(stderr,
3515                                       "Applied patch ", patch, " cleanly.\n");
3516                return 0;
3517        }
3518
3519        /* This should not happen, because a removal patch that leaves
3520         * contents are marked "rejected" at the patch level.
3521         */
3522        if (!patch->new_name)
3523                die("internal error");
3524
3525        /* Say this even without --verbose */
3526        say_patch_name(stderr, "Applying patch ", patch, " with");
3527        fprintf(stderr, " %d rejects...\n", cnt);
3528
3529        cnt = strlen(patch->new_name);
3530        if (ARRAY_SIZE(namebuf) <= cnt + 5) {
3531                cnt = ARRAY_SIZE(namebuf) - 5;
3532                warning("truncating .rej filename to %.*s.rej",
3533                        cnt - 1, patch->new_name);
3534        }
3535        memcpy(namebuf, patch->new_name, cnt);
3536        memcpy(namebuf + cnt, ".rej", 5);
3537
3538        rej = fopen(namebuf, "w");
3539        if (!rej)
3540                return error("cannot open %s: %s", namebuf, strerror(errno));
3541
3542        /* Normal git tools never deal with .rej, so do not pretend
3543         * this is a git patch by saying --git nor give extended
3544         * headers.  While at it, maybe please "kompare" that wants
3545         * the trailing TAB and some garbage at the end of line ;-).
3546         */
3547        fprintf(rej, "diff a/%s b/%s\t(rejected hunks)\n",
3548                patch->new_name, patch->new_name);
3549        for (cnt = 1, frag = patch->fragments;
3550             frag;
3551             cnt++, frag = frag->next) {
3552                if (!frag->rejected) {
3553                        fprintf(stderr, "Hunk #%d applied cleanly.\n", cnt);
3554                        continue;
3555                }
3556                fprintf(stderr, "Rejected hunk #%d.\n", cnt);
3557                fprintf(rej, "%.*s", frag->size, frag->patch);
3558                if (frag->patch[frag->size-1] != '\n')
3559                        fputc('\n', rej);
3560        }
3561        fclose(rej);
3562        return -1;
3563}
3564
3565static int write_out_results(struct patch *list, int skipped_patch)
3566{
3567        int phase;
3568        int errs = 0;
3569        struct patch *l;
3570
3571        if (!list && !skipped_patch)
3572                return error("No changes");
3573
3574        for (phase = 0; phase < 2; phase++) {
3575                l = list;
3576                while (l) {
3577                        if (l->rejected)
3578                                errs = 1;
3579                        else {
3580                                write_out_one_result(l, phase);
3581                                if (phase == 1 && write_out_one_reject(l))
3582                                        errs = 1;
3583                        }
3584                        l = l->next;
3585                }
3586        }
3587        return errs;
3588}
3589
3590static struct lock_file lock_file;
3591
3592static struct string_list limit_by_name;
3593static int has_include;
3594static void add_name_limit(const char *name, int exclude)
3595{
3596        struct string_list_item *it;
3597
3598        it = string_list_append(&limit_by_name, name);
3599        it->util = exclude ? NULL : (void *) 1;
3600}
3601
3602static int use_patch(struct patch *p)
3603{
3604        const char *pathname = p->new_name ? p->new_name : p->old_name;
3605        int i;
3606
3607        /* Paths outside are not touched regardless of "--include" */
3608        if (0 < prefix_length) {
3609                int pathlen = strlen(pathname);
3610                if (pathlen <= prefix_length ||
3611                    memcmp(prefix, pathname, prefix_length))
3612                        return 0;
3613        }
3614
3615        /* See if it matches any of exclude/include rule */
3616        for (i = 0; i < limit_by_name.nr; i++) {
3617                struct string_list_item *it = &limit_by_name.items[i];
3618                if (!fnmatch(it->string, pathname, 0))
3619                        return (it->util != NULL);
3620        }
3621
3622        /*
3623         * If we had any include, a path that does not match any rule is
3624         * not used.  Otherwise, we saw bunch of exclude rules (or none)
3625         * and such a path is used.
3626         */
3627        return !has_include;
3628}
3629
3630
3631static void prefix_one(char **name)
3632{
3633        char *old_name = *name;
3634        if (!old_name)
3635                return;
3636        *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
3637        free(old_name);
3638}
3639
3640static void prefix_patches(struct patch *p)
3641{
3642        if (!prefix || p->is_toplevel_relative)
3643                return;
3644        for ( ; p; p = p->next) {
3645                if (p->new_name == p->old_name) {
3646                        char *prefixed = p->new_name;
3647                        prefix_one(&prefixed);
3648                        p->new_name = p->old_name = prefixed;
3649                }
3650                else {
3651                        prefix_one(&p->new_name);
3652                        prefix_one(&p->old_name);
3653                }
3654        }
3655}
3656
3657#define INACCURATE_EOF  (1<<0)
3658#define RECOUNT         (1<<1)
3659
3660static int apply_patch(int fd, const char *filename, int options)
3661{
3662        size_t offset;
3663        struct strbuf buf = STRBUF_INIT;
3664        struct patch *list = NULL, **listp = &list;
3665        int skipped_patch = 0;
3666
3667        /* FIXME - memory leak when using multiple patch files as inputs */
3668        memset(&fn_table, 0, sizeof(struct string_list));
3669        patch_input_file = filename;
3670        read_patch_file(&buf, fd);
3671        offset = 0;
3672        while (offset < buf.len) {
3673                struct patch *patch;
3674                int nr;
3675
3676                patch = xcalloc(1, sizeof(*patch));
3677                patch->inaccurate_eof = !!(options & INACCURATE_EOF);
3678                patch->recount =  !!(options & RECOUNT);
3679                nr = parse_chunk(buf.buf + offset, buf.len - offset, patch);
3680                if (nr < 0)
3681                        break;
3682                if (apply_in_reverse)
3683                        reverse_patches(patch);
3684                if (prefix)
3685                        prefix_patches(patch);
3686                if (use_patch(patch)) {
3687                        patch_stats(patch);
3688                        *listp = patch;
3689                        listp = &patch->next;
3690                }
3691                else {
3692                        /* perhaps free it a bit better? */
3693                        free(patch);
3694                        skipped_patch++;
3695                }
3696                offset += nr;
3697        }
3698
3699        if (whitespace_error && (ws_error_action == die_on_ws_error))
3700                apply = 0;
3701
3702        update_index = check_index && apply;
3703        if (update_index && newfd < 0)
3704                newfd = hold_locked_index(&lock_file, 1);
3705
3706        if (check_index) {
3707                if (read_cache() < 0)
3708                        die("unable to read index file");
3709        }
3710
3711        if ((check || apply) &&
3712            check_patch_list(list) < 0 &&
3713            !apply_with_reject)
3714                exit(1);
3715
3716        if (apply && write_out_results(list, skipped_patch))
3717                exit(1);
3718
3719        if (fake_ancestor)
3720                build_fake_ancestor(list, fake_ancestor);
3721
3722        if (diffstat)
3723                stat_patch_list(list);
3724
3725        if (numstat)
3726                numstat_patch_list(list);
3727
3728        if (summary)
3729                summary_patch_list(list);
3730
3731        strbuf_release(&buf);
3732        return 0;
3733}
3734
3735static int git_apply_config(const char *var, const char *value, void *cb)
3736{
3737        if (!strcmp(var, "apply.whitespace"))
3738                return git_config_string(&apply_default_whitespace, var, value);
3739        else if (!strcmp(var, "apply.ignorewhitespace"))
3740                return git_config_string(&apply_default_ignorewhitespace, var, value);
3741        return git_default_config(var, value, cb);
3742}
3743
3744static int option_parse_exclude(const struct option *opt,
3745                                const char *arg, int unset)
3746{
3747        add_name_limit(arg, 1);
3748        return 0;
3749}
3750
3751static int option_parse_include(const struct option *opt,
3752                                const char *arg, int unset)
3753{
3754        add_name_limit(arg, 0);
3755        has_include = 1;
3756        return 0;
3757}
3758
3759static int option_parse_p(const struct option *opt,
3760                          const char *arg, int unset)
3761{
3762        p_value = atoi(arg);
3763        p_value_known = 1;
3764        return 0;
3765}
3766
3767static int option_parse_z(const struct option *opt,
3768                          const char *arg, int unset)
3769{
3770        if (unset)
3771                line_termination = '\n';
3772        else
3773                line_termination = 0;
3774        return 0;
3775}
3776
3777static int option_parse_space_change(const struct option *opt,
3778                          const char *arg, int unset)
3779{
3780        if (unset)
3781                ws_ignore_action = ignore_ws_none;
3782        else
3783                ws_ignore_action = ignore_ws_change;
3784        return 0;
3785}
3786
3787static int option_parse_whitespace(const struct option *opt,
3788                                   const char *arg, int unset)
3789{
3790        const char **whitespace_option = opt->value;
3791
3792        *whitespace_option = arg;
3793        parse_whitespace_option(arg);
3794        return 0;
3795}
3796
3797static int option_parse_directory(const struct option *opt,
3798                                  const char *arg, int unset)
3799{
3800        root_len = strlen(arg);
3801        if (root_len && arg[root_len - 1] != '/') {
3802                char *new_root;
3803                root = new_root = xmalloc(root_len + 2);
3804                strcpy(new_root, arg);
3805                strcpy(new_root + root_len++, "/");
3806        } else
3807                root = arg;
3808        return 0;
3809}
3810
3811int cmd_apply(int argc, const char **argv, const char *prefix_)
3812{
3813        int i;
3814        int errs = 0;
3815        int is_not_gitdir = !startup_info->have_repository;
3816        int binary;
3817        int force_apply = 0;
3818
3819        const char *whitespace_option = NULL;
3820
3821        struct option builtin_apply_options[] = {
3822                { OPTION_CALLBACK, 0, "exclude", NULL, "path",
3823                        "don't apply changes matching the given path",
3824                        0, option_parse_exclude },
3825                { OPTION_CALLBACK, 0, "include", NULL, "path",
3826                        "apply changes matching the given path",
3827                        0, option_parse_include },
3828                { OPTION_CALLBACK, 'p', NULL, NULL, "num",
3829                        "remove <num> leading slashes from traditional diff paths",
3830                        0, option_parse_p },
3831                OPT_BOOLEAN(0, "no-add", &no_add,
3832                        "ignore additions made by the patch"),
3833                OPT_BOOLEAN(0, "stat", &diffstat,
3834                        "instead of applying the patch, output diffstat for the input"),
3835                { OPTION_BOOLEAN, 0, "allow-binary-replacement", &binary,
3836                  NULL, "old option, now no-op",
3837                  PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },
3838                { OPTION_BOOLEAN, 0, "binary", &binary,
3839                  NULL, "old option, now no-op",
3840                  PARSE_OPT_HIDDEN | PARSE_OPT_NOARG },
3841                OPT_BOOLEAN(0, "numstat", &numstat,
3842                        "shows number of added and deleted lines in decimal notation"),
3843                OPT_BOOLEAN(0, "summary", &summary,
3844                        "instead of applying the patch, output a summary for the input"),
3845                OPT_BOOLEAN(0, "check", &check,
3846                        "instead of applying the patch, see if the patch is applicable"),
3847                OPT_BOOLEAN(0, "index", &check_index,
3848                        "make sure the patch is applicable to the current index"),
3849                OPT_BOOLEAN(0, "cached", &cached,
3850                        "apply a patch without touching the working tree"),
3851                OPT_BOOLEAN(0, "apply", &force_apply,
3852                        "also apply the patch (use with --stat/--summary/--check)"),
3853                OPT_FILENAME(0, "build-fake-ancestor", &fake_ancestor,
3854                        "build a temporary index based on embedded index information"),
3855                { OPTION_CALLBACK, 'z', NULL, NULL, NULL,
3856                        "paths are separated with NUL character",
3857                        PARSE_OPT_NOARG, option_parse_z },
3858                OPT_INTEGER('C', NULL, &p_context,
3859                                "ensure at least <n> lines of context match"),
3860                { OPTION_CALLBACK, 0, "whitespace", &whitespace_option, "action",
3861                        "detect new or modified lines that have whitespace errors",
3862                        0, option_parse_whitespace },
3863                { OPTION_CALLBACK, 0, "ignore-space-change", NULL, NULL,
3864                        "ignore changes in whitespace when finding context",
3865                        PARSE_OPT_NOARG, option_parse_space_change },
3866                { OPTION_CALLBACK, 0, "ignore-whitespace", NULL, NULL,
3867                        "ignore changes in whitespace when finding context",
3868                        PARSE_OPT_NOARG, option_parse_space_change },
3869                OPT_BOOLEAN('R', "reverse", &apply_in_reverse,
3870                        "apply the patch in reverse"),
3871                OPT_BOOLEAN(0, "unidiff-zero", &unidiff_zero,
3872                        "don't expect at least one line of context"),
3873                OPT_BOOLEAN(0, "reject", &apply_with_reject,
3874                        "leave the rejected hunks in corresponding *.rej files"),
3875                OPT__VERBOSE(&apply_verbosely, "be verbose"),
3876                OPT_BIT(0, "inaccurate-eof", &options,
3877                        "tolerate incorrectly detected missing new-line at the end of file",
3878                        INACCURATE_EOF),
3879                OPT_BIT(0, "recount", &options,
3880                        "do not trust the line counts in the hunk headers",
3881                        RECOUNT),
3882                { OPTION_CALLBACK, 0, "directory", NULL, "root",
3883                        "prepend <root> to all filenames",
3884                        0, option_parse_directory },
3885                OPT_END()
3886        };
3887
3888        prefix = prefix_;
3889        prefix_length = prefix ? strlen(prefix) : 0;
3890        git_config(git_apply_config, NULL);
3891        if (apply_default_whitespace)
3892                parse_whitespace_option(apply_default_whitespace);
3893        if (apply_default_ignorewhitespace)
3894                parse_ignorewhitespace_option(apply_default_ignorewhitespace);
3895
3896        argc = parse_options(argc, argv, prefix, builtin_apply_options,
3897                        apply_usage, 0);
3898
3899        if (apply_with_reject)
3900                apply = apply_verbosely = 1;
3901        if (!force_apply && (diffstat || numstat || summary || check || fake_ancestor))
3902                apply = 0;
3903        if (check_index && is_not_gitdir)
3904                die("--index outside a repository");
3905        if (cached) {
3906                if (is_not_gitdir)
3907                        die("--cached outside a repository");
3908                check_index = 1;
3909        }
3910        for (i = 0; i < argc; i++) {
3911                const char *arg = argv[i];
3912                int fd;
3913
3914                if (!strcmp(arg, "-")) {
3915                        errs |= apply_patch(0, "<stdin>", options);
3916                        read_stdin = 0;
3917                        continue;
3918                } else if (0 < prefix_length)
3919                        arg = prefix_filename(prefix, prefix_length, arg);
3920
3921                fd = open(arg, O_RDONLY);
3922                if (fd < 0)
3923                        die_errno("can't open patch '%s'", arg);
3924                read_stdin = 0;
3925                set_default_whitespace_mode(whitespace_option);
3926                errs |= apply_patch(fd, arg, options);
3927                close(fd);
3928        }
3929        set_default_whitespace_mode(whitespace_option);
3930        if (read_stdin)
3931                errs |= apply_patch(0, "<stdin>", options);
3932        if (whitespace_error) {
3933                if (squelch_whitespace_errors &&
3934                    squelch_whitespace_errors < whitespace_error) {
3935                        int squelched =
3936                                whitespace_error - squelch_whitespace_errors;
3937                        warning("squelched %d "
3938                                "whitespace error%s",
3939                                squelched,
3940                                squelched == 1 ? "" : "s");
3941                }
3942                if (ws_error_action == die_on_ws_error)
3943                        die("%d line%s add%s whitespace errors.",
3944                            whitespace_error,
3945                            whitespace_error == 1 ? "" : "s",
3946                            whitespace_error == 1 ? "s" : "");
3947                if (applied_after_fixing_ws && apply)
3948                        warning("%d line%s applied after"
3949                                " fixing whitespace errors.",
3950                                applied_after_fixing_ws,
3951                                applied_after_fixing_ws == 1 ? "" : "s");
3952                else if (whitespace_error)
3953                        warning("%d line%s add%s whitespace errors.",
3954                                whitespace_error,
3955                                whitespace_error == 1 ? "" : "s",
3956                                whitespace_error == 1 ? "s" : "");
3957        }
3958
3959        if (update_index) {
3960                if (write_cache(newfd, active_cache, active_nr) ||
3961                    commit_locked_index(&lock_file))
3962                        die("Unable to write new index file");
3963        }
3964
3965        return !!errs;
3966}