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