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