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