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