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