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