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