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