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