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