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