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