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