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