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