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