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