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