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