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