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