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