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