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