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