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