packaging: Add contrib installation
[platform/upstream/git.git] / apply.c
diff --git a/apply.c b/apply.c
index 7a9f4c8..668b16e 100644 (file)
--- a/apply.c
+++ b/apply.c
@@ -8,6 +8,8 @@
  */
 
 #include "cache.h"
+#include "config.h"
+#include "object-store.h"
 #include "blob.h"
 #include "delta.h"
 #include "diff.h"
 #include "rerere.h"
 #include "apply.h"
 
+struct gitdiff_data {
+       struct strbuf *root;
+       int linenr;
+       int p_value;
+};
+
 static void git_apply_config(void)
 {
-       git_config_get_string_const("apply.whitespace", &apply_default_whitespace);
-       git_config_get_string_const("apply.ignorewhitespace", &apply_default_ignorewhitespace);
-       git_config(git_default_config, NULL);
+       git_config_get_string("apply.whitespace", &apply_default_whitespace);
+       git_config_get_string("apply.ignorewhitespace", &apply_default_ignorewhitespace);
+       git_config(git_xmerge_config, NULL);
 }
 
 static int parse_whitespace_option(struct apply_state *state, const char *option)
@@ -54,6 +62,10 @@ static int parse_whitespace_option(struct apply_state *state, const char *option
                state->ws_error_action = correct_ws_error;
                return 0;
        }
+       /*
+        * Please update $__git_whitespacelist in git-completion.bash
+        * when you add new options.
+        */
        return error(_("unrecognized whitespace option '%s'"), option);
 }
 
@@ -74,14 +86,12 @@ static int parse_ignorewhitespace_option(struct apply_state *state,
 }
 
 int init_apply_state(struct apply_state *state,
-                    const char *prefix,
-                    struct lock_file *lock_file)
+                    struct repository *repo,
+                    const char *prefix)
 {
        memset(state, 0, sizeof(*state));
        state->prefix = prefix;
-       state->prefix_length = state->prefix ? strlen(state->prefix) : 0;
-       state->lock_file = lock_file;
-       state->newfd = -1;
+       state->repo = repo;
        state->apply = 1;
        state->line_termination = '\n';
        state->p_value = 1;
@@ -144,10 +154,10 @@ int check_apply_state(struct apply_state *state, int force_apply)
                        return error(_("--cached outside a repository"));
                state->check_index = 1;
        }
+       if (state->ita_only && (state->check_index || is_not_gitdir))
+               state->ita_only = 0;
        if (state->check_index)
                state->unsafe_paths = 0;
-       if (!state->lock_file)
-               return error("BUG: state->lock_file should not be NULL");
 
        if (state->apply_verbosity <= verbosity_silent) {
                state->saved_error_routine = get_error_routine();
@@ -197,39 +207,6 @@ struct fragment {
 #define BINARY_DELTA_DEFLATED  1
 #define BINARY_LITERAL_DEFLATED 2
 
-/*
- * This represents a "patch" to a file, both metainfo changes
- * such as creation/deletion, filemode and content changes represented
- * as a series of fragments.
- */
-struct patch {
-       char *new_name, *old_name, *def_name;
-       unsigned int old_mode, new_mode;
-       int is_new, is_delete;  /* -1 = unknown, 0 = false, 1 = true */
-       int rejected;
-       unsigned ws_rule;
-       int lines_added, lines_deleted;
-       int score;
-       int extension_linenr; /* first line specifying delete/new/rename/copy */
-       unsigned int is_toplevel_relative:1;
-       unsigned int inaccurate_eof:1;
-       unsigned int is_binary:1;
-       unsigned int is_copy:1;
-       unsigned int is_rename:1;
-       unsigned int recount:1;
-       unsigned int conflicted_threeway:1;
-       unsigned int direct_to_threeway:1;
-       struct fragment *fragments;
-       char *result;
-       size_t resultsize;
-       char old_sha1_prefix[41];
-       char new_sha1_prefix[41];
-       struct patch *next;
-
-       /* three-way fallback result */
-       struct object_id threeway_stage[3];
-};
-
 static void free_fragment_list(struct fragment *list)
 {
        while (list) {
@@ -304,52 +281,33 @@ static uint32_t hash_line(const char *cp, size_t len)
 static int fuzzy_matchlines(const char *s1, size_t n1,
                            const char *s2, size_t n2)
 {
-       const char *last1 = s1 + n1 - 1;
-       const char *last2 = s2 + n2 - 1;
-       int result = 0;
+       const char *end1 = s1 + n1;
+       const char *end2 = s2 + n2;
 
        /* ignore line endings */
-       while ((*last1 == '\r') || (*last1 == '\n'))
-               last1--;
-       while ((*last2 == '\r') || (*last2 == '\n'))
-               last2--;
-
-       /* skip leading whitespaces, if both begin with whitespace */
-       if (s1 <= last1 && s2 <= last2 && isspace(*s1) && isspace(*s2)) {
-               while (isspace(*s1) && (s1 <= last1))
-                       s1++;
-               while (isspace(*s2) && (s2 <= last2))
-                       s2++;
-       }
-       /* early return if both lines are empty */
-       if ((s1 > last1) && (s2 > last2))
-               return 1;
-       while (!result) {
-               result = *s1++ - *s2++;
-               /*
-                * Skip whitespace inside. We check for whitespace on
-                * both buffers because we don't want "a b" to match
-                * "ab"
-                */
-               if (isspace(*s1) && isspace(*s2)) {
-                       while (isspace(*s1) && s1 <= last1)
+       while (s1 < end1 && (end1[-1] == '\r' || end1[-1] == '\n'))
+               end1--;
+       while (s2 < end2 && (end2[-1] == '\r' || end2[-1] == '\n'))
+               end2--;
+
+       while (s1 < end1 && s2 < end2) {
+               if (isspace(*s1)) {
+                       /*
+                        * Skip whitespace. We check on both buffers
+                        * because we don't want "a b" to match "ab".
+                        */
+                       if (!isspace(*s2))
+                               return 0;
+                       while (s1 < end1 && isspace(*s1))
                                s1++;
-                       while (isspace(*s2) && s2 <= last2)
+                       while (s2 < end2 && isspace(*s2))
                                s2++;
-               }
-               /*
-                * If we reached the end on one side only,
-                * lines don't match
-                */
-               if (
-                   ((s2 > last2) && (s1 <= last1)) ||
-                   ((s1 > last1) && (s2 <= last2)))
+               } else if (*s1++ != *s2++)
                        return 0;
-               if ((s1 > last1) && (s2 > last2))
-                       break;
        }
 
-       return !result;
+       /* If we reached the end on one side only, lines don't match. */
+       return s1 == end1 && s2 == end2;
 }
 
 static void add_line_info(struct image *img, const char *bol, size_t len, unsigned flag)
@@ -483,9 +441,8 @@ static char *squash_slash(char *name)
        return name;
 }
 
-static char *find_name_gnu(struct apply_state *state,
+static char *find_name_gnu(struct strbuf *root,
                           const char *line,
-                          const char *def,
                           int p_value)
 {
        struct strbuf name = STRBUF_INIT;
@@ -493,7 +450,7 @@ static char *find_name_gnu(struct apply_state *state,
 
        /*
         * Proposed "new-style" GNU patch/diff format; see
-        * http://marc.info/?l=git&m=112927316408690&w=2
+        * https://lore.kernel.org/git/7vll0wvb2a.fsf@assigned-by-dhcp.cox.net/
         */
        if (unquote_c_style(&name, line, NULL)) {
                strbuf_release(&name);
@@ -510,8 +467,8 @@ static char *find_name_gnu(struct apply_state *state,
        }
 
        strbuf_remove(&name, 0, cp - name.buf);
-       if (state->root.len)
-               strbuf_insert(&name, 0, state->root.buf, state->root.len);
+       if (root->len)
+               strbuf_insert(&name, 0, root->buf, root->len);
        return squash_slash(strbuf_detach(&name, NULL));
 }
 
@@ -674,7 +631,7 @@ static size_t diff_timestamp_len(const char *line, size_t len)
        return line + len - end;
 }
 
-static char *find_name_common(struct apply_state *state,
+static char *find_name_common(struct strbuf *root,
                              const char *line,
                              const char *def,
                              int p_value,
@@ -717,30 +674,30 @@ static char *find_name_common(struct apply_state *state,
                        return squash_slash(xstrdup(def));
        }
 
-       if (state->root.len) {
-               char *ret = xstrfmt("%s%.*s", state->root.buf, len, start);
+       if (root->len) {
+               char *ret = xstrfmt("%s%.*s", root->buf, len, start);
                return squash_slash(ret);
        }
 
        return squash_slash(xmemdupz(start, len));
 }
 
-static char *find_name(struct apply_state *state,
+static char *find_name(struct strbuf *root,
                       const char *line,
                       char *def,
                       int p_value,
                       int terminate)
 {
        if (*line == '"') {
-               char *name = find_name_gnu(state, line, def, p_value);
+               char *name = find_name_gnu(root, line, p_value);
                if (name)
                        return name;
        }
 
-       return find_name_common(state, line, def, p_value, NULL, terminate);
+       return find_name_common(root, line, def, p_value, NULL, terminate);
 }
 
-static char *find_name_traditional(struct apply_state *state,
+static char *find_name_traditional(struct strbuf *root,
                                   const char *line,
                                   char *def,
                                   int p_value)
@@ -749,7 +706,7 @@ static char *find_name_traditional(struct apply_state *state,
        size_t date_len;
 
        if (*line == '"') {
-               char *name = find_name_gnu(state, line, def, p_value);
+               char *name = find_name_gnu(root, line, p_value);
                if (name)
                        return name;
        }
@@ -757,21 +714,10 @@ static char *find_name_traditional(struct apply_state *state,
        len = strchrnul(line, '\n') - line;
        date_len = diff_timestamp_len(line, len);
        if (!date_len)
-               return find_name_common(state, line, def, p_value, NULL, TERM_TAB);
+               return find_name_common(root, line, def, p_value, NULL, TERM_TAB);
        len -= date_len;
 
-       return find_name_common(state, line, def, p_value, line + len, 0);
-}
-
-static int count_slashes(const char *cp)
-{
-       int cnt = 0;
-       char ch;
-
-       while ((ch = *cp++))
-               if (ch == '/')
-                       cnt++;
-       return cnt;
+       return find_name_common(root, line, def, p_value, line + len, 0);
 }
 
 /*
@@ -785,7 +731,7 @@ static int guess_p_value(struct apply_state *state, const char *nameline)
 
        if (is_dev_null(nameline))
                return -1;
-       name = find_name_traditional(state, nameline, NULL, 0);
+       name = find_name_traditional(&state->root, nameline, NULL, 0);
        if (!name)
                return -1;
        cp = strchr(name, '/');
@@ -796,11 +742,11 @@ static int guess_p_value(struct apply_state *state, const char *nameline)
                 * Does it begin with "a/$our-prefix" and such?  Then this is
                 * very likely to apply to our directory.
                 */
-               if (!strncmp(name, state->prefix, state->prefix_length))
+               if (starts_with(name, state->prefix))
                        val = count_slashes(state->prefix);
                else {
                        cp++;
-                       if (!strncmp(cp, state->prefix, state->prefix_length))
+                       if (starts_with(cp, state->prefix))
                                val = count_slashes(state->prefix) + 1;
                }
        }
@@ -822,16 +768,13 @@ static int has_epoch_timestamp(const char *nameline)
         * 1970-01-01, and the seconds part must be "00".
         */
        const char stamp_regexp[] =
-               "^(1969-12-31|1970-01-01)"
-               " "
-               "[0-2][0-9]:[0-5][0-9]:00(\\.0+)?"
+               "^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
                " "
                "([-+][0-2][0-9]:?[0-5][0-9])\n";
        const char *timestamp = NULL, *cp, *colon;
        static regex_t *stamp;
        regmatch_t m[10];
-       int zoneoffset;
-       int hourminute;
+       int zoneoffset, epoch_hour, hour, minute;
        int status;
 
        for (cp = nameline; *cp != '\n'; cp++) {
@@ -840,6 +783,18 @@ static int has_epoch_timestamp(const char *nameline)
        }
        if (!timestamp)
                return 0;
+
+       /*
+        * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
+        * (west of GMT) or 1970-01-01 (east of GMT)
+        */
+       if (skip_prefix(timestamp, "1969-12-31 ", &timestamp))
+               epoch_hour = 24;
+       else if (skip_prefix(timestamp, "1970-01-01 ", &timestamp))
+               epoch_hour = 0;
+       else
+               return 0;
+
        if (!stamp) {
                stamp = xmalloc(sizeof(*stamp));
                if (regcomp(stamp, stamp_regexp, REG_EXTENDED)) {
@@ -857,6 +812,9 @@ static int has_epoch_timestamp(const char *nameline)
                return 0;
        }
 
+       hour = strtol(timestamp, NULL, 10);
+       minute = strtol(timestamp + m[1].rm_so, NULL, 10);
+
        zoneoffset = strtol(timestamp + m[3].rm_so + 1, (char **) &colon, 10);
        if (*colon == ':')
                zoneoffset = zoneoffset * 60 + strtol(colon + 1, NULL, 10);
@@ -865,20 +823,7 @@ static int has_epoch_timestamp(const char *nameline)
        if (timestamp[m[3].rm_so] == '-')
                zoneoffset = -zoneoffset;
 
-       /*
-        * YYYY-MM-DD hh:mm:ss must be from either 1969-12-31
-        * (west of GMT) or 1970-01-01 (east of GMT)
-        */
-       if ((zoneoffset < 0 && memcmp(timestamp, "1969-12-31", 10)) ||
-           (0 <= zoneoffset && memcmp(timestamp, "1970-01-01", 10)))
-               return 0;
-
-       hourminute = (strtol(timestamp + 11, NULL, 10) * 60 +
-                     strtol(timestamp + 14, NULL, 10) -
-                     zoneoffset);
-
-       return ((zoneoffset < 0 && hourminute == 1440) ||
-               (0 <= zoneoffset && !hourminute));
+       return hour * 60 + minute - zoneoffset == epoch_hour * 60;
 }
 
 /*
@@ -910,17 +855,17 @@ static int parse_traditional_patch(struct apply_state *state,
        if (is_dev_null(first)) {
                patch->is_new = 1;
                patch->is_delete = 0;
-               name = find_name_traditional(state, second, NULL, state->p_value);
+               name = find_name_traditional(&state->root, second, NULL, state->p_value);
                patch->new_name = name;
        } else if (is_dev_null(second)) {
                patch->is_new = 0;
                patch->is_delete = 1;
-               name = find_name_traditional(state, first, NULL, state->p_value);
+               name = find_name_traditional(&state->root, first, NULL, state->p_value);
                patch->old_name = name;
        } else {
                char *first_name;
-               first_name = find_name_traditional(state, first, NULL, state->p_value);
-               name = find_name_traditional(state, second, first_name, state->p_value);
+               first_name = find_name_traditional(&state->root, first, NULL, state->p_value);
+               name = find_name_traditional(&state->root, second, first_name, state->p_value);
                free(first_name);
                if (has_epoch_timestamp(first)) {
                        patch->is_new = 1;
@@ -941,7 +886,7 @@ static int parse_traditional_patch(struct apply_state *state,
        return 0;
 }
 
-static int gitdiff_hdrend(struct apply_state *state,
+static int gitdiff_hdrend(struct gitdiff_data *state,
                          const char *line,
                          struct patch *patch)
 {
@@ -960,25 +905,24 @@ static int gitdiff_hdrend(struct apply_state *state,
 #define DIFF_OLD_NAME 0
 #define DIFF_NEW_NAME 1
 
-static int gitdiff_verify_name(struct apply_state *state,
+static int gitdiff_verify_name(struct gitdiff_data *state,
                               const char *line,
                               int isnull,
                               char **name,
                               int side)
 {
        if (!*name && !isnull) {
-               *name = find_name(state, line, NULL, state->p_value, TERM_TAB);
+               *name = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
                return 0;
        }
 
        if (*name) {
-               int len = strlen(*name);
                char *another;
                if (isnull)
                        return error(_("git apply: bad git-diff - expected /dev/null, got %s on line %d"),
                                     *name, state->linenr);
-               another = find_name(state, line, NULL, state->p_value, TERM_TAB);
-               if (!another || memcmp(another, *name, len + 1)) {
+               another = find_name(state->root, line, NULL, state->p_value, TERM_TAB);
+               if (!another || strcmp(another, *name)) {
                        free(another);
                        return error((side == DIFF_NEW_NAME) ?
                            _("git apply: bad git-diff - inconsistent new filename on line %d") :
@@ -986,15 +930,14 @@ static int gitdiff_verify_name(struct apply_state *state,
                }
                free(another);
        } else {
-               /* expect "/dev/null" */
-               if (memcmp("/dev/null", line, 9) || line[9] != '\n')
+               if (!is_dev_null(line))
                        return error(_("git apply: bad git-diff - expected /dev/null on line %d"), state->linenr);
        }
 
        return 0;
 }
 
-static int gitdiff_oldname(struct apply_state *state,
+static int gitdiff_oldname(struct gitdiff_data *state,
                           const char *line,
                           struct patch *patch)
 {
@@ -1003,7 +946,7 @@ static int gitdiff_oldname(struct apply_state *state,
                                   DIFF_OLD_NAME);
 }
 
-static int gitdiff_newname(struct apply_state *state,
+static int gitdiff_newname(struct gitdiff_data *state,
                           const char *line,
                           struct patch *patch)
 {
@@ -1021,21 +964,21 @@ static int parse_mode_line(const char *line, int linenr, unsigned int *mode)
        return 0;
 }
 
-static int gitdiff_oldmode(struct apply_state *state,
+static int gitdiff_oldmode(struct gitdiff_data *state,
                           const char *line,
                           struct patch *patch)
 {
        return parse_mode_line(line, state->linenr, &patch->old_mode);
 }
 
-static int gitdiff_newmode(struct apply_state *state,
+static int gitdiff_newmode(struct gitdiff_data *state,
                           const char *line,
                           struct patch *patch)
 {
        return parse_mode_line(line, state->linenr, &patch->new_mode);
 }
 
-static int gitdiff_delete(struct apply_state *state,
+static int gitdiff_delete(struct gitdiff_data *state,
                          const char *line,
                          struct patch *patch)
 {
@@ -1045,7 +988,7 @@ static int gitdiff_delete(struct apply_state *state,
        return gitdiff_oldmode(state, line, patch);
 }
 
-static int gitdiff_newfile(struct apply_state *state,
+static int gitdiff_newfile(struct gitdiff_data *state,
                           const char *line,
                           struct patch *patch)
 {
@@ -1055,47 +998,47 @@ static int gitdiff_newfile(struct apply_state *state,
        return gitdiff_newmode(state, line, patch);
 }
 
-static int gitdiff_copysrc(struct apply_state *state,
+static int gitdiff_copysrc(struct gitdiff_data *state,
                           const char *line,
                           struct patch *patch)
 {
        patch->is_copy = 1;
        free(patch->old_name);
-       patch->old_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
+       patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
        return 0;
 }
 
-static int gitdiff_copydst(struct apply_state *state,
+static int gitdiff_copydst(struct gitdiff_data *state,
                           const char *line,
                           struct patch *patch)
 {
        patch->is_copy = 1;
        free(patch->new_name);
-       patch->new_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
+       patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
        return 0;
 }
 
-static int gitdiff_renamesrc(struct apply_state *state,
+static int gitdiff_renamesrc(struct gitdiff_data *state,
                             const char *line,
                             struct patch *patch)
 {
        patch->is_rename = 1;
        free(patch->old_name);
-       patch->old_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
+       patch->old_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
        return 0;
 }
 
-static int gitdiff_renamedst(struct apply_state *state,
+static int gitdiff_renamedst(struct gitdiff_data *state,
                             const char *line,
                             struct patch *patch)
 {
        patch->is_rename = 1;
        free(patch->new_name);
-       patch->new_name = find_name(state, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
+       patch->new_name = find_name(state->root, line, NULL, state->p_value ? state->p_value - 1 : 0, 0);
        return 0;
 }
 
-static int gitdiff_similarity(struct apply_state *state,
+static int gitdiff_similarity(struct gitdiff_data *state,
                              const char *line,
                              struct patch *patch)
 {
@@ -1105,7 +1048,7 @@ static int gitdiff_similarity(struct apply_state *state,
        return 0;
 }
 
-static int gitdiff_dissimilarity(struct apply_state *state,
+static int gitdiff_dissimilarity(struct gitdiff_data *state,
                                 const char *line,
                                 struct patch *patch)
 {
@@ -1115,7 +1058,7 @@ static int gitdiff_dissimilarity(struct apply_state *state,
        return 0;
 }
 
-static int gitdiff_index(struct apply_state *state,
+static int gitdiff_index(struct gitdiff_data *state,
                         const char *line,
                         struct patch *patch)
 {
@@ -1125,13 +1068,14 @@ static int gitdiff_index(struct apply_state *state,
         */
        const char *ptr, *eol;
        int len;
+       const unsigned hexsz = the_hash_algo->hexsz;
 
        ptr = strchr(line, '.');
-       if (!ptr || ptr[1] != '.' || 40 < ptr - line)
+       if (!ptr || ptr[1] != '.' || hexsz < ptr - line)
                return 0;
        len = ptr - line;
-       memcpy(patch->old_sha1_prefix, line, len);
-       patch->old_sha1_prefix[len] = 0;
+       memcpy(patch->old_oid_prefix, line, len);
+       patch->old_oid_prefix[len] = 0;
 
        line = ptr + 2;
        ptr = strchr(line, ' ');
@@ -1141,10 +1085,10 @@ static int gitdiff_index(struct apply_state *state,
                ptr = eol;
        len = ptr - line;
 
-       if (40 < len)
+       if (hexsz < len)
                return 0;
-       memcpy(patch->new_sha1_prefix, line, len);
-       patch->new_sha1_prefix[len] = 0;
+       memcpy(patch->new_oid_prefix, line, len);
+       patch->new_oid_prefix[len] = 0;
        if (*ptr == ' ')
                return gitdiff_oldmode(state, ptr + 1, patch);
        return 0;
@@ -1154,7 +1098,7 @@ static int gitdiff_index(struct apply_state *state,
  * This is normal for a diff that doesn't change anything: we'll fall through
  * into the next diff. Tell the parser to break out.
  */
-static int gitdiff_unrecognized(struct apply_state *state,
+static int gitdiff_unrecognized(struct gitdiff_data *state,
                                const char *line,
                                struct patch *patch)
 {
@@ -1165,17 +1109,17 @@ static int gitdiff_unrecognized(struct apply_state *state,
  * Skip p_value leading components from "line"; as we do not accept
  * absolute paths, return NULL in that case.
  */
-static const char *skip_tree_prefix(struct apply_state *state,
+static const char *skip_tree_prefix(int p_value,
                                    const char *line,
                                    int llen)
 {
        int nslash;
        int i;
 
-       if (!state->p_value)
+       if (!p_value)
                return (llen && line[0] == '/') ? NULL : line;
 
-       nslash = state->p_value;
+       nslash = p_value;
        for (i = 0; i < llen; i++) {
                int ch = line[i];
                if (ch == '/' && --nslash <= 0)
@@ -1192,7 +1136,7 @@ static const char *skip_tree_prefix(struct apply_state *state,
  * creation or deletion of an empty file.  In any of these cases,
  * both sides are the same name under a/ and b/ respectively.
  */
-static char *git_header_name(struct apply_state *state,
+static char *git_header_name(int p_value,
                             const char *line,
                             int llen)
 {
@@ -1212,7 +1156,7 @@ static char *git_header_name(struct apply_state *state,
                        goto free_and_fail1;
 
                /* strip the a/b prefix including trailing slash */
-               cp = skip_tree_prefix(state, first.buf, first.len);
+               cp = skip_tree_prefix(p_value, first.buf, first.len);
                if (!cp)
                        goto free_and_fail1;
                strbuf_remove(&first, 0, cp - first.buf);
@@ -1229,7 +1173,7 @@ static char *git_header_name(struct apply_state *state,
                if (*second == '"') {
                        if (unquote_c_style(&sp, second, NULL))
                                goto free_and_fail1;
-                       cp = skip_tree_prefix(state, sp.buf, sp.len);
+                       cp = skip_tree_prefix(p_value, sp.buf, sp.len);
                        if (!cp)
                                goto free_and_fail1;
                        /* They must match, otherwise ignore */
@@ -1240,7 +1184,7 @@ static char *git_header_name(struct apply_state *state,
                }
 
                /* unquoted second */
-               cp = skip_tree_prefix(state, second, line + llen - second);
+               cp = skip_tree_prefix(p_value, second, line + llen - second);
                if (!cp)
                        goto free_and_fail1;
                if (line + llen - cp != first.len ||
@@ -1255,7 +1199,7 @@ static char *git_header_name(struct apply_state *state,
        }
 
        /* unquoted first name */
-       name = skip_tree_prefix(state, line, llen);
+       name = skip_tree_prefix(p_value, line, llen);
        if (!name)
                return NULL;
 
@@ -1271,7 +1215,7 @@ static char *git_header_name(struct apply_state *state,
                        if (unquote_c_style(&sp, second, NULL))
                                goto free_and_fail2;
 
-                       np = skip_tree_prefix(state, sp.buf, sp.len);
+                       np = skip_tree_prefix(p_value, sp.buf, sp.len);
                        if (!np)
                                goto free_and_fail2;
 
@@ -1315,7 +1259,7 @@ static char *git_header_name(struct apply_state *state,
                         */
                        if (!name[len + 1])
                                return NULL; /* no postimage name */
-                       second = skip_tree_prefix(state, name + len + 1,
+                       second = skip_tree_prefix(p_value, name + len + 1,
                                                  line_len - (len + 1));
                        if (!second)
                                return NULL;
@@ -1330,26 +1274,28 @@ static char *git_header_name(struct apply_state *state,
        }
 }
 
-static int check_header_line(struct apply_state *state, struct patch *patch)
+static int check_header_line(int linenr, struct patch *patch)
 {
        int extensions = (patch->is_delete == 1) + (patch->is_new == 1) +
                         (patch->is_rename == 1) + (patch->is_copy == 1);
        if (extensions > 1)
                return error(_("inconsistent header lines %d and %d"),
-                            patch->extension_linenr, state->linenr);
+                            patch->extension_linenr, linenr);
        if (extensions && !patch->extension_linenr)
-               patch->extension_linenr = state->linenr;
+               patch->extension_linenr = linenr;
        return 0;
 }
 
-/* Verify that we recognize the lines following a git header */
-static int parse_git_header(struct apply_state *state,
-                           const char *line,
-                           int len,
-                           unsigned int size,
-                           struct patch *patch)
+int parse_git_diff_header(struct strbuf *root,
+                         int *linenr,
+                         int p_value,
+                         const char *line,
+                         int len,
+                         unsigned int size,
+                         struct patch *patch)
 {
        unsigned long offset;
+       struct gitdiff_data parse_hdr_state;
 
        /* A git diff has explicit new/delete information, so we don't guess */
        patch->is_new = 0;
@@ -1361,20 +1307,24 @@ static int parse_git_header(struct apply_state *state,
         * or removing or adding empty files), so we get
         * the default name from the header.
         */
-       patch->def_name = git_header_name(state, line, len);
-       if (patch->def_name && state->root.len) {
-               char *s = xstrfmt("%s%s", state->root.buf, patch->def_name);
+       patch->def_name = git_header_name(p_value, line, len);
+       if (patch->def_name && root->len) {
+               char *s = xstrfmt("%s%s", root->buf, patch->def_name);
                free(patch->def_name);
                patch->def_name = s;
        }
 
        line += len;
        size -= len;
-       state->linenr++;
-       for (offset = len ; size > 0 ; offset += len, size -= len, line += len, state->linenr++) {
+       (*linenr)++;
+       parse_hdr_state.root = root;
+       parse_hdr_state.linenr = *linenr;
+       parse_hdr_state.p_value = p_value;
+
+       for (offset = len ; size > 0 ; offset += len, size -= len, line += len, (*linenr)++) {
                static const struct opentry {
                        const char *str;
-                       int (*fn)(struct apply_state *, const char *, struct patch *);
+                       int (*fn)(struct gitdiff_data *, const char *, struct patch *);
                } optable[] = {
                        { "@@ -", gitdiff_hdrend },
                        { "--- ", gitdiff_oldname },
@@ -1405,17 +1355,38 @@ static int parse_git_header(struct apply_state *state,
                        int res;
                        if (len < oplen || memcmp(p->str, line, oplen))
                                continue;
-                       res = p->fn(state, line + oplen, patch);
+                       res = p->fn(&parse_hdr_state, line + oplen, patch);
                        if (res < 0)
                                return -1;
-                       if (check_header_line(state, patch))
+                       if (check_header_line(*linenr, patch))
                                return -1;
                        if (res > 0)
-                               return offset;
+                               goto done;
                        break;
                }
        }
 
+done:
+       if (!patch->old_name && !patch->new_name) {
+               if (!patch->def_name) {
+                       error(Q_("git diff header lacks filename information when removing "
+                                "%d leading pathname component (line %d)",
+                                "git diff header lacks filename information when removing "
+                                "%d leading pathname components (line %d)",
+                                parse_hdr_state.p_value),
+                             parse_hdr_state.p_value, *linenr);
+                       return -128;
+               }
+               patch->old_name = xstrdup(patch->def_name);
+               patch->new_name = xstrdup(patch->def_name);
+       }
+       if ((!patch->new_name && !patch->is_delete) ||
+           (!patch->old_name && !patch->is_new)) {
+               error(_("git diff header lacks filename information "
+                       "(line %d)"), *linenr);
+               return -128;
+       }
+       patch->is_toplevel_relative = 1;
        return offset;
 }
 
@@ -1589,31 +1560,13 @@ static int find_header(struct apply_state *state,
                 * or mode change, so we handle that specially
                 */
                if (!memcmp("diff --git ", line, 11)) {
-                       int git_hdr_len = parse_git_header(state, line, len, size, patch);
+                       int git_hdr_len = parse_git_diff_header(&state->root, &state->linenr,
+                                                               state->p_value, line, len,
+                                                               size, patch);
                        if (git_hdr_len < 0)
                                return -128;
                        if (git_hdr_len <= len)
                                continue;
-                       if (!patch->old_name && !patch->new_name) {
-                               if (!patch->def_name) {
-                                       error(Q_("git diff header lacks filename information when removing "
-                                                       "%d leading pathname component (line %d)",
-                                                       "git diff header lacks filename information when removing "
-                                                       "%d leading pathname components (line %d)",
-                                                       state->p_value),
-                                                    state->p_value, state->linenr);
-                                       return -128;
-                               }
-                               patch->old_name = xstrdup(patch->def_name);
-                               patch->new_name = xstrdup(patch->def_name);
-                       }
-                       if ((!patch->new_name && !patch->is_delete) ||
-                           (!patch->old_name && !patch->is_new)) {
-                               error(_("git diff header lacks filename information "
-                                            "(line %d)"), state->linenr);
-                               return -128;
-                       }
-                       patch->is_toplevel_relative = 1;
                        *hdrsize = git_hdr_len;
                        return offset;
                }
@@ -1675,6 +1628,19 @@ static void check_whitespace(struct apply_state *state,
 }
 
 /*
+ * Check if the patch has context lines with CRLF or
+ * the patch wants to remove lines with CRLF.
+ */
+static void check_old_for_crlf(struct patch *patch, const char *line, int len)
+{
+       if (len >= 2 && line[len-1] == '\n' && line[len-2] == '\r') {
+               patch->ws_rule |= WS_CR_AT_EOL;
+               patch->crlf_in_old = 1;
+       }
+}
+
+
+/*
  * Parse a unified diff. Note that this really needs to parse each
  * fragment separately, since the only way to know the difference
  * between a "---" that is part of a patch, and a "---" that starts
@@ -1724,11 +1690,14 @@ static int parse_fragment(struct apply_state *state,
                        if (!deleted && !added)
                                leading++;
                        trailing++;
+                       check_old_for_crlf(patch, line, len);
                        if (!state->apply_in_reverse &&
                            state->ws_error_action == correct_ws_error)
                                check_whitespace(state, line, len, patch->ws_rule);
                        break;
                case '-':
+                       if (!state->apply_in_reverse)
+                               check_old_for_crlf(patch, line, len);
                        if (state->apply_in_reverse &&
                            state->ws_error_action != nowarn_ws_error)
                                check_whitespace(state, line, len, patch->ws_rule);
@@ -1737,6 +1706,8 @@ static int parse_fragment(struct apply_state *state,
                        trailing = 0;
                        break;
                case '+':
+                       if (state->apply_in_reverse)
+                               check_old_for_crlf(patch, line, len);
                        if (!state->apply_in_reverse &&
                            state->ws_error_action != nowarn_ws_error)
                                check_whitespace(state, line, len, patch->ws_rule);
@@ -1761,7 +1732,7 @@ static int parse_fragment(struct apply_state *state,
        }
        if (oldlines || newlines)
                return -1;
-       if (!deleted && !added)
+       if (!patch->recount && !deleted && !added)
                return -1;
 
        fragment->leading = leading;
@@ -2101,17 +2072,16 @@ static int use_patch(struct apply_state *state, struct patch *p)
        int i;
 
        /* Paths outside are not touched regardless of "--include" */
-       if (0 < state->prefix_length) {
-               int pathlen = strlen(pathname);
-               if (pathlen <= state->prefix_length ||
-                   memcmp(state->prefix, pathname, state->prefix_length))
+       if (state->prefix && *state->prefix) {
+               const char *rest;
+               if (!skip_prefix(pathname, state->prefix, &rest) || !*rest)
                        return 0;
        }
 
        /* See if it matches any of exclude/include rule */
        for (i = 0; i < state->limit_by_name.nr; i++) {
                struct string_list_item *it = &state->limit_by_name.items[i];
-               if (!wildmatch(it->string, pathname, 0, NULL))
+               if (!wildmatch(it->string, pathname, 0))
                        return (it->util != NULL);
        }
 
@@ -2146,10 +2116,12 @@ static int parse_chunk(struct apply_state *state, char *buffer, unsigned long si
 
        if (!use_patch(state, patch))
                patch->ws_rule = 0;
+       else if (patch->new_name)
+               patch->ws_rule = whitespace_rule(state->repo->index,
+                                                patch->new_name);
        else
-               patch->ws_rule = whitespace_rule(patch->new_name
-                                                ? patch->new_name
-                                                : patch->old_name);
+               patch->ws_rule = whitespace_rule(state->repo->index,
+                                                patch->old_name);
 
        patchsize = parse_single_patch(state,
                                       buffer + offset + hdrsize,
@@ -2219,7 +2191,7 @@ static void reverse_patches(struct patch *p)
                SWAP(p->new_mode, p->old_mode);
                SWAP(p->is_new, p->is_delete);
                SWAP(p->lines_added, p->lines_deleted);
-               SWAP(p->old_sha1_prefix, p->new_sha1_prefix);
+               SWAP(p->old_oid_prefix, p->new_oid_prefix);
 
                for (; frag; frag = frag->next) {
                        SWAP(frag->newpos, frag->oldpos);
@@ -2280,8 +2252,11 @@ static void show_stats(struct apply_state *state, struct patch *patch)
                add, pluses, del, minuses);
 }
 
-static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
+static int read_old_data(struct stat *st, struct patch *patch,
+                        const char *path, struct strbuf *buf)
 {
+       int conv_flags = patch->crlf_in_old ?
+               CONV_EOL_KEEP_CRLF : CONV_EOL_RENORMALIZE;
        switch (st->st_mode & S_IFMT) {
        case S_IFLNK:
                if (strbuf_readlink(buf, path, st->st_size) < 0)
@@ -2290,7 +2265,15 @@ static int read_old_data(struct stat *st, const char *path, struct strbuf *buf)
        case S_IFREG:
                if (strbuf_read_file(buf, path, st->st_size) != st->st_size)
                        return error(_("unable to open or read %s"), path);
-               convert_to_git(path, buf->buf, buf->len, buf, 0);
+               /*
+                * "git apply" without "--index/--cached" should never look
+                * at the index; the target file may not have been added to
+                * the index yet, and we may not even be in any Git repository.
+                * Pass NULL to convert_to_git() to stress this; the function
+                * should never look at the index when explicit crlf option
+                * is given.
+                */
+               convert_to_git(NULL, path, buf->buf, buf->len, buf, conv_flags);
                return 0;
        default:
                return -1;
@@ -2310,7 +2293,7 @@ static void update_pre_post_images(struct image *preimage,
                                   size_t len, size_t postlen)
 {
        int i, ctx, reduced;
-       char *new, *old, *fixed;
+       char *new_buf, *old_buf, *fixed;
        struct image fixed_preimage;
 
        /*
@@ -2336,25 +2319,25 @@ static void update_pre_post_images(struct image *preimage,
         * We trust the caller to tell us if the update can be done
         * in place (postlen==0) or not.
         */
-       old = postimage->buf;
+       old_buf = postimage->buf;
        if (postlen)
-               new = postimage->buf = xmalloc(postlen);
+               new_buf = postimage->buf = xmalloc(postlen);
        else
-               new = old;
+               new_buf = old_buf;
        fixed = preimage->buf;
 
        for (i = reduced = ctx = 0; i < postimage->nr; i++) {
                size_t l_len = postimage->line[i].len;
                if (!(postimage->line[i].flag & LINE_COMMON)) {
                        /* an added line -- no counterparts in preimage */
-                       memmove(new, old, l_len);
-                       old += l_len;
-                       new += l_len;
+                       memmove(new_buf, old_buf, l_len);
+                       old_buf += l_len;
+                       new_buf += l_len;
                        continue;
                }
 
                /* a common context -- skip it in the original postimage */
-               old += l_len;
+               old_buf += l_len;
 
                /* and find the corresponding one in the fixed preimage */
                while (ctx < preimage->nr &&
@@ -2374,29 +2357,29 @@ static void update_pre_post_images(struct image *preimage,
 
                /* and copy it in, while fixing the line length */
                l_len = preimage->line[ctx].len;
-               memcpy(new, fixed, l_len);
-               new += l_len;
+               memcpy(new_buf, fixed, l_len);
+               new_buf += l_len;
                fixed += l_len;
                postimage->line[i].len = l_len;
                ctx++;
        }
 
        if (postlen
-           ? postlen < new - postimage->buf
-           : postimage->len < new - postimage->buf)
-               die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
-                   (int)postlen, (int) postimage->len, (int)(new - postimage->buf));
+           ? postlen < new_buf - postimage->buf
+           : postimage->len < new_buf - postimage->buf)
+               BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
+                   (int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));
 
        /* Fix the length of the whole thing */
-       postimage->len = new - postimage->buf;
+       postimage->len = new_buf - postimage->buf;
        postimage->nr -= reduced;
 }
 
 static int line_by_line_fuzzy_match(struct image *img,
                                    struct image *preimage,
                                    struct image *postimage,
-                                   unsigned long try,
-                                   int try_lno,
+                                   unsigned long current,
+                                   int current_lno,
                                    int preimage_limit)
 {
        int i;
@@ -2413,9 +2396,9 @@ static int line_by_line_fuzzy_match(struct image *img,
 
        for (i = 0; i < preimage_limit; i++) {
                size_t prelen = preimage->line[i].len;
-               size_t imglen = img->line[try_lno+i].len;
+               size_t imglen = img->line[current_lno+i].len;
 
-               if (!fuzzy_matchlines(img->buf + try + imgoff, imglen,
+               if (!fuzzy_matchlines(img->buf + current + imgoff, imglen,
                                      preimage->buf + preoff, prelen))
                        return 0;
                if (preimage->line[i].flag & LINE_COMMON)
@@ -2452,7 +2435,7 @@ static int line_by_line_fuzzy_match(struct image *img,
         */
        extra_chars = preimage_end - preimage_eof;
        strbuf_init(&fixed, imgoff + extra_chars);
-       strbuf_add(&fixed, img->buf + try, imgoff);
+       strbuf_add(&fixed, img->buf + current, imgoff);
        strbuf_add(&fixed, preimage_eof, extra_chars);
        fixed_buf = strbuf_detach(&fixed, &fixed_len);
        update_pre_post_images(preimage, postimage,
@@ -2464,8 +2447,8 @@ static int match_fragment(struct apply_state *state,
                          struct image *img,
                          struct image *preimage,
                          struct image *postimage,
-                         unsigned long try,
-                         int try_lno,
+                         unsigned long current,
+                         int current_lno,
                          unsigned ws_rule,
                          int match_beginning, int match_end)
 {
@@ -2475,12 +2458,12 @@ static int match_fragment(struct apply_state *state,
        size_t fixed_len, postlen;
        int preimage_limit;
 
-       if (preimage->nr + try_lno <= img->nr) {
+       if (preimage->nr + current_lno <= img->nr) {
                /*
                 * The hunk falls within the boundaries of img.
                 */
                preimage_limit = preimage->nr;
-               if (match_end && (preimage->nr + try_lno != img->nr))
+               if (match_end && (preimage->nr + current_lno != img->nr))
                        return 0;
        } else if (state->ws_error_action == correct_ws_error &&
                   (ws_rule & WS_BLANK_AT_EOF)) {
@@ -2491,7 +2474,7 @@ static int match_fragment(struct apply_state *state,
                 * match with img, and the remainder of the preimage
                 * must be blank.
                 */
-               preimage_limit = img->nr - try_lno;
+               preimage_limit = img->nr - current_lno;
        } else {
                /*
                 * The hunk extends beyond the end of the img and
@@ -2501,27 +2484,27 @@ static int match_fragment(struct apply_state *state,
                return 0;
        }
 
-       if (match_beginning && try_lno)
+       if (match_beginning && current_lno)
                return 0;
 
        /* Quick hash check */
        for (i = 0; i < preimage_limit; i++)
-               if ((img->line[try_lno + i].flag & LINE_PATCHED) ||
-                   (preimage->line[i].hash != img->line[try_lno + i].hash))
+               if ((img->line[current_lno + i].flag & LINE_PATCHED) ||
+                   (preimage->line[i].hash != img->line[current_lno + i].hash))
                        return 0;
 
        if (preimage_limit == preimage->nr) {
                /*
                 * Do we have an exact match?  If we were told to match
-                * at the end, size must be exactly at try+fragsize,
-                * otherwise try+fragsize must be still within the preimage,
+                * at the end, size must be exactly at current+fragsize,
+                * otherwise current+fragsize must be still within the preimage,
                 * and either case, the old piece should match the preimage
                 * exactly.
                 */
                if ((match_end
-                    ? (try + preimage->len == img->len)
-                    : (try + preimage->len <= img->len)) &&
-                   !memcmp(img->buf + try, preimage->buf, preimage->len))
+                    ? (current + preimage->len == img->len)
+                    : (current + preimage->len <= img->len)) &&
+                   !memcmp(img->buf + current, preimage->buf, preimage->len))
                        return 1;
        } else {
                /*
@@ -2552,7 +2535,7 @@ static int match_fragment(struct apply_state *state,
         */
        if (state->ws_ignore_action == ignore_ws_change)
                return line_by_line_fuzzy_match(img, preimage, postimage,
-                                               try, try_lno, preimage_limit);
+                                               current, current_lno, preimage_limit);
 
        if (state->ws_error_action != correct_ws_error)
                return 0;
@@ -2586,10 +2569,10 @@ static int match_fragment(struct apply_state *state,
         */
        strbuf_init(&fixed, preimage->len + 1);
        orig = preimage->buf;
-       target = img->buf + try;
+       target = img->buf + current;
        for (i = 0; i < preimage_limit; i++) {
                size_t oldlen = preimage->line[i].len;
-               size_t tgtlen = img->line[try_lno + i].len;
+               size_t tgtlen = img->line[current_lno + i].len;
                size_t fixstart = fixed.len;
                struct strbuf tgtfix;
                int match;
@@ -2675,8 +2658,18 @@ static int find_pos(struct apply_state *state,
                    int match_beginning, int match_end)
 {
        int i;
-       unsigned long backwards, forwards, try;
-       int backwards_lno, forwards_lno, try_lno;
+       unsigned long backwards, forwards, current;
+       int backwards_lno, forwards_lno, current_lno;
+
+       /*
+        * When running with --allow-overlap, it is possible that a hunk is
+        * seen that pretends to start at the beginning (but no longer does),
+        * and that *still* needs to match the end. So trust `match_end` more
+        * than `match_beginning`.
+        */
+       if (state->allow_overlap && match_beginning && match_end &&
+           img->nr - preimage->nr != 0)
+               match_beginning = 0;
 
        /*
         * If match_beginning or match_end is specified, there is no
@@ -2696,25 +2689,25 @@ static int find_pos(struct apply_state *state,
        if ((size_t) line > img->nr)
                line = img->nr;
 
-       try = 0;
+       current = 0;
        for (i = 0; i < line; i++)
-               try += img->line[i].len;
+               current += img->line[i].len;
 
        /*
         * There's probably some smart way to do this, but I'll leave
         * that to the smart and beautiful people. I'm simple and stupid.
         */
-       backwards = try;
+       backwards = current;
        backwards_lno = line;
-       forwards = try;
+       forwards = current;
        forwards_lno = line;
-       try_lno = line;
+       current_lno = line;
 
        for (i = 0; ; i++) {
                if (match_fragment(state, img, preimage, postimage,
-                                  try, try_lno, ws_rule,
+                                  current, current_lno, ws_rule,
                                   match_beginning, match_end))
-                       return try_lno;
+                       return current_lno;
 
        again:
                if (backwards_lno == 0 && forwards_lno == img->nr)
@@ -2727,8 +2720,8 @@ static int find_pos(struct apply_state *state,
                        }
                        backwards_lno--;
                        backwards -= img->line[backwards_lno].len;
-                       try = backwards;
-                       try_lno = backwards_lno;
+                       current = backwards;
+                       current_lno = backwards_lno;
                } else {
                        if (forwards_lno == img->nr) {
                                i++;
@@ -2736,8 +2729,8 @@ static int find_pos(struct apply_state *state,
                        }
                        forwards += img->line[forwards_lno].len;
                        forwards_lno++;
-                       try = forwards;
-                       try_lno = forwards_lno;
+                       current = forwards;
+                       current_lno = forwards_lno;
                }
 
        }
@@ -2821,13 +2814,10 @@ static void update_image(struct apply_state *state,
                img->line_allocated = img->line;
        }
        if (preimage_limit != postimage->nr)
-               memmove(img->line + applied_pos + postimage->nr,
-                       img->line + applied_pos + preimage_limit,
-                       (img->nr - (applied_pos + preimage_limit)) *
-                       sizeof(*img->line));
-       memcpy(img->line + applied_pos,
-              postimage->line,
-              postimage->nr * sizeof(*img->line));
+               MOVE_ARRAY(img->line + applied_pos + postimage->nr,
+                          img->line + applied_pos + preimage_limit,
+                          img->nr - (applied_pos + preimage_limit));
+       COPY_ARRAY(img->line + applied_pos, postimage->line, postimage->nr);
        if (!state->allow_overlap)
                for (i = 0; i < postimage->nr; i++)
                        img->line[applied_pos + i].flag |= LINE_PATCHED;
@@ -2908,6 +2898,7 @@ static int apply_one_fragment(struct apply_state *state,
                        if (plen && (ws_rule & WS_BLANK_AT_EOF) &&
                            ws_blank_line(patch + 1, plen, ws_rule))
                                is_blank_context = 1;
+                       /* fallthrough */
                case '-':
                        memcpy(old, patch + 1, plen);
                        add_line_info(&preimage, old, plen,
@@ -2915,7 +2906,7 @@ static int apply_one_fragment(struct apply_state *state,
                        old += plen;
                        if (first == '-')
                                break;
-               /* Fall-through for ' ' */
+                       /* fallthrough */
                case '+':
                        /* --no-add does not add new lines */
                        if (first == '+' && state->no_add)
@@ -2964,6 +2955,8 @@ static int apply_one_fragment(struct apply_state *state,
            newlines.len > 0 && newlines.buf[newlines.len - 1] == '\n') {
                old--;
                strbuf_setlen(&newlines, newlines.len - 1);
+               preimage.line_allocated[preimage.nr - 1].len--;
+               postimage.line_allocated[postimage.nr - 1].len--;
        }
 
        leading = frag->leading;
@@ -3146,15 +3139,16 @@ static int apply_binary(struct apply_state *state,
 {
        const char *name = patch->old_name ? patch->old_name : patch->new_name;
        struct object_id oid;
+       const unsigned hexsz = the_hash_algo->hexsz;
 
        /*
         * For safety, we require patch index line to contain
-        * full 40-byte textual SHA1 for old and new, at least for now.
+        * full hex textual object ID for old and new, at least for now.
         */
-       if (strlen(patch->old_sha1_prefix) != 40 ||
-           strlen(patch->new_sha1_prefix) != 40 ||
-           get_oid_hex(patch->old_sha1_prefix, &oid) ||
-           get_oid_hex(patch->new_sha1_prefix, &oid))
+       if (strlen(patch->old_oid_prefix) != hexsz ||
+           strlen(patch->new_oid_prefix) != hexsz ||
+           get_oid_hex(patch->old_oid_prefix, &oid) ||
+           get_oid_hex(patch->new_oid_prefix, &oid))
                return error(_("cannot apply binary patch to '%s' "
                               "without full index line"), name);
 
@@ -3163,8 +3157,9 @@ static int apply_binary(struct apply_state *state,
                 * See if the old one matches what the patch
                 * applies to.
                 */
-               hash_sha1_file(img->buf, img->len, blob_type, oid.hash);
-               if (strcmp(oid_to_hex(&oid), patch->old_sha1_prefix))
+               hash_object_file(the_hash_algo, img->buf, img->len, blob_type,
+                                &oid);
+               if (strcmp(oid_to_hex(&oid), patch->old_oid_prefix))
                        return error(_("the patch applies to '%s' (%s), "
                                       "which does not match the "
                                       "current contents."),
@@ -3177,23 +3172,23 @@ static int apply_binary(struct apply_state *state,
                                       "'%s' but it is not empty"), name);
        }
 
-       get_oid_hex(patch->new_sha1_prefix, &oid);
+       get_oid_hex(patch->new_oid_prefix, &oid);
        if (is_null_oid(&oid)) {
                clear_image(img);
                return 0; /* deletion patch */
        }
 
-       if (has_sha1_file(oid.hash)) {
+       if (has_object(the_repository, &oid, 0)) {
                /* We already have the postimage */
                enum object_type type;
                unsigned long size;
                char *result;
 
-               result = read_sha1_file(oid.hash, &type, &size);
+               result = read_object_file(&oid, &type, &size);
                if (!result)
                        return error(_("the necessary postimage %s for "
                                       "'%s' cannot be read"),
-                                    patch->new_sha1_prefix, name);
+                                    patch->new_oid_prefix, name);
                clear_image(img);
                img->buf = result;
                img->len = size;
@@ -3208,10 +3203,11 @@ static int apply_binary(struct apply_state *state,
                                     name);
 
                /* verify that the result matches */
-               hash_sha1_file(img->buf, img->len, blob_type, oid.hash);
-               if (strcmp(oid_to_hex(&oid), patch->new_sha1_prefix))
+               hash_object_file(the_hash_algo, img->buf, img->len, blob_type,
+                                &oid);
+               if (strcmp(oid_to_hex(&oid), patch->new_oid_prefix))
                        return error(_("binary patch to '%s' creates incorrect result (expecting %s, got %s)"),
-                               name, patch->new_sha1_prefix, oid_to_hex(&oid));
+                               name, patch->new_oid_prefix, oid_to_hex(&oid));
        }
 
        return 0;
@@ -3251,7 +3247,7 @@ static int read_blob_object(struct strbuf *buf, const struct object_id *oid, uns
                unsigned long sz;
                char *result;
 
-               result = read_sha1_file(oid->hash, &type, &sz);
+               result = read_object_file(oid, &type, &sz);
                if (!result)
                        return -1;
                /* XXX read_sha1_file NUL-terminates */
@@ -3352,7 +3348,8 @@ static int checkout_target(struct index_state *istate,
 
        costate.refresh_cache = 1;
        costate.istate = istate;
-       if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))
+       if (checkout_entry(ce, &costate, NULL, NULL) ||
+           lstat(ce->name, st))
                return error(_("cannot checkout %s"), ce->name);
        return 0;
 }
@@ -3380,14 +3377,17 @@ static struct patch *previous_patch(struct apply_state *state,
        return previous;
 }
 
-static int verify_index_match(const struct cache_entry *ce, struct stat *st)
+static int verify_index_match(struct apply_state *state,
+                             const struct cache_entry *ce,
+                             struct stat *st)
 {
        if (S_ISGITLINK(ce->ce_mode)) {
                if (!S_ISDIR(st->st_mode))
                        return -1;
                return 0;
        }
-       return ce_match_stat(ce, st, CE_MATCH_IGNORE_VALID|CE_MATCH_IGNORE_SKIP_WORKTREE);
+       return ie_match_stat(state->repo->index, ce, st,
+                            CE_MATCH_IGNORE_VALID | CE_MATCH_IGNORE_SKIP_WORKTREE);
 }
 
 #define SUBMODULE_PATCH_WITHOUT_INDEX 1
@@ -3396,6 +3396,7 @@ static int load_patch_target(struct apply_state *state,
                             struct strbuf *buf,
                             const struct cache_entry *ce,
                             struct stat *st,
+                            struct patch *patch,
                             const char *name,
                             unsigned expected_mode)
 {
@@ -3411,7 +3412,7 @@ static int load_patch_target(struct apply_state *state,
                } else if (has_symlink_leading_path(name, strlen(name))) {
                        return error(_("reading from '%s' beyond a symbolic link"), name);
                } else {
-                       if (read_old_data(st, name, buf))
+                       if (read_old_data(st, patch, name, buf))
                                return error(_("failed to read %s"), name);
                }
        }
@@ -3444,7 +3445,7 @@ static int load_preimage(struct apply_state *state,
                /* We have a patched copy in memory; use that. */
                strbuf_add(&buf, previous->result, previous->resultsize);
        } else {
-               status = load_patch_target(state, &buf, ce, st,
+               status = load_patch_target(state, &buf, ce, st, patch,
                                           patch->old_name, patch->old_mode);
                if (status < 0)
                        return status;
@@ -3467,7 +3468,8 @@ static int load_preimage(struct apply_state *state,
        return 0;
 }
 
-static int three_way_merge(struct image *image,
+static int three_way_merge(struct apply_state *state,
+                          struct image *image,
                           char *path,
                           const struct object_id *base,
                           const struct object_id *ours,
@@ -3483,7 +3485,9 @@ static int three_way_merge(struct image *image,
        status = ll_merge(&result, path,
                          &base_file, "base",
                          &our_file, "ours",
-                         &their_file, "theirs", NULL);
+                         &their_file, "theirs",
+                         state->repo->index,
+                         NULL);
        free(base_file.ptr);
        free(our_file.ptr);
        free(their_file.ptr);
@@ -3517,22 +3521,22 @@ static int load_current(struct apply_state *state,
        unsigned mode = patch->new_mode;
 
        if (!patch->is_new)
-               die("BUG: patch to %s is not a creation", patch->old_name);
+               BUG("patch to %s is not a creation", patch->old_name);
 
-       pos = cache_name_pos(name, strlen(name));
+       pos = index_name_pos(state->repo->index, name, strlen(name));
        if (pos < 0)
                return error(_("%s: does not exist in index"), name);
-       ce = active_cache[pos];
+       ce = state->repo->index->cache[pos];
        if (lstat(name, &st)) {
                if (errno != ENOENT)
                        return error_errno("%s", name);
-               if (checkout_target(&the_index, ce, &st))
+               if (checkout_target(state->repo->index, ce, &st))
                        return -1;
        }
-       if (verify_index_match(ce, &st))
+       if (verify_index_match(state, ce, &st))
                return error(_("%s: does not match index"), name);
 
-       status = load_patch_target(state, &buf, ce, &st, name, mode);
+       status = load_patch_target(state, &buf, ce, &st, patch, name, mode);
        if (status < 0)
                return status;
        else if (status)
@@ -3562,8 +3566,8 @@ static int try_threeway(struct apply_state *state,
 
        /* Preimage the patch was prepared for */
        if (patch->is_new)
-               write_sha1_file("", 0, blob_type, pre_oid.hash);
-       else if (get_sha1(patch->old_sha1_prefix, pre_oid.hash) ||
+               write_object_file("", 0, blob_type, &pre_oid);
+       else if (get_oid(patch->old_oid_prefix, &pre_oid) ||
                 read_blob_object(&buf, &pre_oid, patch->old_mode))
                return error(_("repository lacks the necessary blob to fall back on 3-way merge."));
 
@@ -3578,7 +3582,7 @@ static int try_threeway(struct apply_state *state,
                return -1;
        }
        /* post_oid is theirs */
-       write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, post_oid.hash);
+       write_object_file(tmp_image.buf, tmp_image.len, blob_type, &post_oid);
        clear_image(&tmp_image);
 
        /* our_oid is ours */
@@ -3591,11 +3595,11 @@ static int try_threeway(struct apply_state *state,
                        return error(_("cannot read the current contents of '%s'"),
                                     patch->old_name);
        }
-       write_sha1_file(tmp_image.buf, tmp_image.len, blob_type, our_oid.hash);
+       write_object_file(tmp_image.buf, tmp_image.len, blob_type, &our_oid);
        clear_image(&tmp_image);
 
        /* in-core three-way merge between post and our using pre as base */
-       status = three_way_merge(image, patch->new_name,
+       status = three_way_merge(state, image, patch->new_name,
                                 &pre_oid, &our_oid, &post_oid);
        if (status < 0) {
                if (state->apply_verbosity > verbosity_silent)
@@ -3688,18 +3692,19 @@ static int check_preimage(struct apply_state *state,
        }
 
        if (state->check_index && !previous) {
-               int pos = cache_name_pos(old_name, strlen(old_name));
+               int pos = index_name_pos(state->repo->index, old_name,
+                                        strlen(old_name));
                if (pos < 0) {
                        if (patch->is_new < 0)
                                goto is_new;
                        return error(_("%s: does not exist in index"), old_name);
                }
-               *ce = active_cache[pos];
+               *ce = state->repo->index->cache[pos];
                if (stat_ret < 0) {
-                       if (checkout_target(&the_index, *ce, st))
+                       if (checkout_target(state->repo->index, *ce, st))
                                return -1;
                }
-               if (!state->cached && verify_index_match(*ce, st))
+               if (!state->cached && verify_index_match(state, *ce, st))
                        return error(_("%s: does not match index"), old_name);
                if (state->cached)
                        st_mode = (*ce)->ce_mode;
@@ -3728,14 +3733,14 @@ static int check_preimage(struct apply_state *state,
  is_new:
        patch->is_new = 1;
        patch->is_delete = 0;
-       free(patch->old_name);
-       patch->old_name = NULL;
+       FREE_AND_NULL(patch->old_name);
        return 0;
 }
 
 
 #define EXISTS_IN_INDEX 1
 #define EXISTS_IN_WORKTREE 2
+#define EXISTS_IN_INDEX_AS_ITA 3
 
 static int check_to_create(struct apply_state *state,
                           const char *new_name,
@@ -3743,10 +3748,23 @@ static int check_to_create(struct apply_state *state,
 {
        struct stat nst;
 
-       if (state->check_index &&
-           cache_name_pos(new_name, strlen(new_name)) >= 0 &&
-           !ok_if_exists)
-               return EXISTS_IN_INDEX;
+       if (state->check_index && (!ok_if_exists || !state->cached)) {
+               int pos;
+
+               pos = index_name_pos(state->repo->index, new_name, strlen(new_name));
+               if (pos >= 0) {
+                       struct cache_entry *ce = state->repo->index->cache[pos];
+
+                       /* allow ITA, as they do not yet exist in the index */
+                       if (!ok_if_exists && !(ce->ce_flags & CE_INTENT_TO_ADD))
+                               return EXISTS_IN_INDEX;
+
+                       /* ITA entries can never match working tree files */
+                       if (!state->cached && (ce->ce_flags & CE_INTENT_TO_ADD))
+                               return EXISTS_IN_INDEX_AS_ITA;
+               }
+       }
+
        if (state->cached)
                return 0;
 
@@ -3764,7 +3782,7 @@ static int check_to_create(struct apply_state *state,
                        return 0;
 
                return EXISTS_IN_WORKTREE;
-       } else if ((errno != ENOENT) && (errno != ENOTDIR)) {
+       } else if (!is_missing_file_error(errno)) {
                return error_errno("%s", new_name);
        }
        return 0;
@@ -3833,7 +3851,8 @@ static int path_is_beyond_symlink_1(struct apply_state *state, struct strbuf *na
                if (state->check_index) {
                        struct cache_entry *ce;
 
-                       ce = cache_file_exists(name->buf, name->len, ignore_case);
+                       ce = index_file_exists(state->repo->index, name->buf,
+                                              name->len, ignore_case);
                        if (ce && S_ISLNK(ce->ce_mode))
                                return 1;
                } else {
@@ -3869,9 +3888,9 @@ static int check_unsafe_path(struct patch *patch)
        if (!patch->is_delete)
                new_name = patch->new_name;
 
-       if (old_name && !verify_path(old_name))
+       if (old_name && !verify_path(old_name, patch->old_mode))
                return error(_("invalid path '%s'"), old_name);
-       if (new_name && !verify_path(new_name))
+       if (new_name && !verify_path(new_name, patch->new_mode))
                return error(_("invalid path '%s'"), new_name);
        return 0;
 }
@@ -3929,7 +3948,8 @@ static int check_patch(struct apply_state *state, struct patch *patch)
                        break; /* happy */
                case EXISTS_IN_INDEX:
                        return error(_("%s: already exists in index"), new_name);
-                       break;
+               case EXISTS_IN_INDEX_AS_ITA:
+                       return error(_("%s: does not match index"), new_name);
                case EXISTS_IN_WORKTREE:
                        return error(_("%s: already exists in working directory"),
                                     new_name);
@@ -4008,9 +4028,10 @@ static int check_patch_list(struct apply_state *state, struct patch *patch)
 static int read_apply_cache(struct apply_state *state)
 {
        if (state->index_file)
-               return read_cache_from(state->index_file);
+               return read_index_from(state->repo->index, state->index_file,
+                                      get_git_dir());
        else
-               return read_cache();
+               return repo_read_index(state->repo);
 }
 
 /* This function tries to read the object name from the current index */
@@ -4021,10 +4042,10 @@ static int get_current_oid(struct apply_state *state, const char *path,
 
        if (read_apply_cache(state) < 0)
                return -1;
-       pos = cache_name_pos(path, strlen(path));
+       pos = index_name_pos(state->repo->index, path, strlen(path));
        if (pos < 0)
                return -1;
-       oidcpy(oid, &active_cache[pos]->oid);
+       oidcpy(oid, &state->repo->index->cache[pos]->oid);
        return 0;
 }
 
@@ -4053,21 +4074,21 @@ static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid)
            starts_with(++preimage, heading) &&
            /* does it record full SHA-1? */
            !get_oid_hex(preimage + sizeof(heading) - 1, oid) &&
-           preimage[sizeof(heading) + GIT_SHA1_HEXSZ - 1] == '\n' &&
+           preimage[sizeof(heading) + the_hash_algo->hexsz - 1] == '\n' &&
            /* does the abbreviated name on the index line agree with it? */
-           starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))
+           starts_with(preimage + sizeof(heading) - 1, p->old_oid_prefix))
                return 0; /* it all looks fine */
 
        /* we may have full object name on the index line */
-       return get_oid_hex(p->old_sha1_prefix, oid);
+       return get_oid_hex(p->old_oid_prefix, oid);
 }
 
-/* Build an index that contains the just the files needed for a 3way merge */
+/* Build an index that contains just the files needed for a 3way merge */
 static int build_fake_ancestor(struct apply_state *state, struct patch *list)
 {
        struct patch *patch;
        struct index_state result = { NULL };
-       static struct lock_file lock;
+       struct lock_file lock = LOCK_INIT;
        int res;
 
        /* Once we start supporting the reverse patch, it may be
@@ -4088,7 +4109,7 @@ static int build_fake_ancestor(struct apply_state *state, struct patch *list)
                        else
                                return error(_("sha1 information is lacking or "
                                               "useless for submodule %s"), name);
-               } else if (!get_sha1_blob(patch->old_sha1_prefix, oid.hash)) {
+               } else if (!get_oid_blob(patch->old_oid_prefix, &oid)) {
                        ; /* ok */
                } else if (!patch->lines_added && !patch->lines_deleted) {
                        /* mode-only change: update the current */
@@ -4099,12 +4120,12 @@ static int build_fake_ancestor(struct apply_state *state, struct patch *list)
                        return error(_("sha1 information is lacking or useless "
                                       "(%s)."), name);
 
-               ce = make_cache_entry(patch->old_mode, oid.hash, name, 0, 0);
+               ce = make_cache_entry(&result, patch->old_mode, &oid, name, 0, 0);
                if (!ce)
                        return error(_("make_cache_entry failed for path '%s'"),
                                     name);
                if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) {
-                       free(ce);
+                       discard_cache_entry(ce);
                        return error(_("could not add %s to temporary index"),
                                     name);
                }
@@ -4172,30 +4193,30 @@ static void show_mode_change(struct patch *p, int show_name)
 static void show_rename_copy(struct patch *p)
 {
        const char *renamecopy = p->is_rename ? "rename" : "copy";
-       const char *old, *new;
+       const char *old_name, *new_name;
 
        /* Find common prefix */
-       old = p->old_name;
-       new = p->new_name;
+       old_name = p->old_name;
+       new_name = p->new_name;
        while (1) {
                const char *slash_old, *slash_new;
-               slash_old = strchr(old, '/');
-               slash_new = strchr(new, '/');
+               slash_old = strchr(old_name, '/');
+               slash_new = strchr(new_name, '/');
                if (!slash_old ||
                    !slash_new ||
-                   slash_old - old != slash_new - new ||
-                   memcmp(old, new, slash_new - new))
+                   slash_old - old_name != slash_new - new_name ||
+                   memcmp(old_name, new_name, slash_new - new_name))
                        break;
-               old = slash_old + 1;
-               new = slash_new + 1;
+               old_name = slash_old + 1;
+               new_name = slash_new + 1;
        }
-       /* p->old_name thru old is the common prefix, and old and new
-        * through the end of names are renames
+       /* p->old_name through old_name is the common prefix, and old_name and
+        * new_name through the end of names are renames
         */
-       if (old != p->old_name)
+       if (old_name != p->old_name)
                printf(" %s %.*s{%s => %s} (%d%%)\n", renamecopy,
-                      (int)(old - p->old_name), p->old_name,
-                      old, new, p->score);
+                      (int)(old_name - p->old_name), p->old_name,
+                      old_name, new_name, p->score);
        else
                printf(" %s %s => %s (%d%%)\n", renamecopy,
                       p->old_name, p->new_name, p->score);
@@ -4251,8 +4272,8 @@ static void patch_stats(struct apply_state *state, struct patch *patch)
 
 static int remove_file(struct apply_state *state, struct patch *patch, int rmdir_empty)
 {
-       if (state->update_index) {
-               if (remove_file_from_cache(patch->old_name) < 0)
+       if (state->update_index && !state->ita_only) {
+               if (remove_file_from_index(state->repo->index, patch->old_name) < 0)
                        return error(_("unable to remove %s from index"), patch->old_name);
        }
        if (!state->cached) {
@@ -4272,42 +4293,41 @@ static int add_index_file(struct apply_state *state,
        struct stat st;
        struct cache_entry *ce;
        int namelen = strlen(path);
-       unsigned ce_size = cache_entry_size(namelen);
 
-       if (!state->update_index)
-               return 0;
-
-       ce = xcalloc(1, ce_size);
+       ce = make_empty_cache_entry(state->repo->index, namelen);
        memcpy(ce->name, path, namelen);
        ce->ce_mode = create_ce_mode(mode);
        ce->ce_flags = create_ce_flags(0);
        ce->ce_namelen = namelen;
-       if (S_ISGITLINK(mode)) {
+       if (state->ita_only) {
+               ce->ce_flags |= CE_INTENT_TO_ADD;
+               set_object_name_for_intent_to_add_entry(ce);
+       } else if (S_ISGITLINK(mode)) {
                const char *s;
 
                if (!skip_prefix(buf, "Subproject commit ", &s) ||
                    get_oid_hex(s, &ce->oid)) {
-                       free(ce);
-                      return error(_("corrupt patch for submodule %s"), path);
+                       discard_cache_entry(ce);
+                       return error(_("corrupt patch for submodule %s"), path);
                }
        } else {
                if (!state->cached) {
                        if (lstat(path, &st) < 0) {
-                               free(ce);
+                               discard_cache_entry(ce);
                                return error_errno(_("unable to stat newly "
                                                     "created file '%s'"),
                                                   path);
                        }
-                       fill_stat_cache_info(ce, &st);
+                       fill_stat_cache_info(state->repo->index, ce, &st);
                }
-               if (write_sha1_file(buf, size, blob_type, ce->oid.hash) < 0) {
-                       free(ce);
+               if (write_object_file(buf, size, blob_type, &ce->oid) < 0) {
+                       discard_cache_entry(ce);
                        return error(_("unable to create backing store "
                                       "for newly created file %s"), path);
                }
        }
-       if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0) {
-               free(ce);
+       if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
+               discard_cache_entry(ce);
                return error(_("unable to add cache entry for %s"), path);
        }
 
@@ -4320,7 +4340,9 @@ static int add_index_file(struct apply_state *state,
  *   0 if everything went well
  *   1 if a recoverable error happened
  */
-static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size)
+static int try_create_file(struct apply_state *state, const char *path,
+                          unsigned int mode, const char *buf,
+                          unsigned long size)
 {
        int fd, res;
        struct strbuf nbuf = STRBUF_INIT;
@@ -4342,7 +4364,7 @@ static int try_create_file(const char *path, unsigned int mode, const char *buf,
        if (fd < 0)
                return 1;
 
-       if (convert_to_working_tree(path, buf, size, &nbuf)) {
+       if (convert_to_working_tree(state->repo->index, path, buf, size, &nbuf, NULL)) {
                size = nbuf.len;
                buf  = nbuf.buf;
        }
@@ -4378,16 +4400,16 @@ static int create_one_file(struct apply_state *state,
        if (state->cached)
                return 0;
 
-       res = try_create_file(path, mode, buf, size);
+       res = try_create_file(state, path, mode, buf, size);
        if (res < 0)
                return -1;
        if (!res)
                return 0;
 
        if (errno == ENOENT) {
-               if (safe_create_leading_directories(path))
+               if (safe_create_leading_directories_no_share(path))
                        return 0;
-               res = try_create_file(path, mode, buf, size);
+               res = try_create_file(state, path, mode, buf, size);
                if (res < 0)
                        return -1;
                if (!res)
@@ -4409,7 +4431,7 @@ static int create_one_file(struct apply_state *state,
                for (;;) {
                        char newpath[PATH_MAX];
                        mksnpath(newpath, sizeof(newpath), "%s~%u", path, nr);
-                       res = try_create_file(newpath, mode, buf, size);
+                       res = try_create_file(state, newpath, mode, buf, size);
                        if (res < 0)
                                return -1;
                        if (!res) {
@@ -4431,27 +4453,26 @@ static int add_conflicted_stages_file(struct apply_state *state,
                                       struct patch *patch)
 {
        int stage, namelen;
-       unsigned ce_size, mode;
+       unsigned mode;
        struct cache_entry *ce;
 
        if (!state->update_index)
                return 0;
        namelen = strlen(patch->new_name);
-       ce_size = cache_entry_size(namelen);
        mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
 
-       remove_file_from_cache(patch->new_name);
+       remove_file_from_index(state->repo->index, patch->new_name);
        for (stage = 1; stage < 4; stage++) {
                if (is_null_oid(&patch->threeway_stage[stage - 1]))
                        continue;
-               ce = xcalloc(1, ce_size);
+               ce = make_empty_cache_entry(state->repo->index, namelen);
                memcpy(ce->name, patch->new_name, namelen);
                ce->ce_mode = create_ce_mode(mode);
                ce->ce_flags = create_ce_flags(stage);
                ce->ce_namelen = namelen;
                oidcpy(&ce->oid, &patch->threeway_stage[stage - 1]);
-               if (add_cache_entry(ce, ADD_CACHE_OK_TO_ADD) < 0) {
-                       free(ce);
+               if (add_index_entry(state->repo->index, ce, ADD_CACHE_OK_TO_ADD) < 0) {
+                       discard_cache_entry(ce);
                        return error(_("unable to add cache entry for %s"),
                                     patch->new_name);
                }
@@ -4474,8 +4495,9 @@ static int create_file(struct apply_state *state, struct patch *patch)
 
        if (patch->conflicted_threeway)
                return add_conflicted_stages_file(state, patch);
-       else
+       else if (state->update_index)
                return add_index_file(state, path, mode, buf, size);
+       return 0;
 }
 
 /* phase zero is to remove, phase one is to create */
@@ -4624,7 +4646,7 @@ static int write_out_results(struct apply_state *state, struct patch *list)
                }
                string_list_clear(&cpath, 0);
 
-               rerere(0);
+               repo_rerere(state->repo, 0);
        }
 
        return errs;
@@ -4649,6 +4671,7 @@ static int apply_patch(struct apply_state *state,
        struct patch *list = NULL, **listp = &list;
        int skipped_patch = 0;
        int res = 0;
+       int flush_attributes = 0;
 
        state->patch_input_file = filename;
        if (read_patch_file(&buf, fd) < 0)
@@ -4674,8 +4697,21 @@ static int apply_patch(struct apply_state *state,
                        reverse_patches(patch);
                if (use_patch(state, patch)) {
                        patch_stats(state, patch);
-                       *listp = patch;
-                       listp = &patch->next;
+                       if (!list || !state->apply_in_reverse) {
+                               *listp = patch;
+                               listp = &patch->next;
+                       } else {
+                               patch->next = list;
+                               list = patch;
+                       }
+
+                       if ((patch->new_name &&
+                            ends_with_path_components(patch->new_name,
+                                                      GITATTRIBUTES_FILE)) ||
+                           (patch->old_name &&
+                            ends_with_path_components(patch->old_name,
+                                                      GITATTRIBUTES_FILE)))
+                               flush_attributes = 1;
                }
                else {
                        if (state->apply_verbosity > verbosity_normal)
@@ -4695,14 +4731,15 @@ static int apply_patch(struct apply_state *state,
        if (state->whitespace_error && (state->ws_error_action == die_on_ws_error))
                state->apply = 0;
 
-       state->update_index = state->check_index && state->apply;
-       if (state->update_index && state->newfd < 0) {
+       state->update_index = (state->check_index || state->ita_only) && state->apply;
+       if (state->update_index && !is_lock_file_locked(&state->lock_file)) {
                if (state->index_file)
-                       state->newfd = hold_lock_file_for_update(state->lock_file,
-                                                                state->index_file,
-                                                                LOCK_DIE_ON_ERROR);
+                       hold_lock_file_for_update(&state->lock_file,
+                                                 state->index_file,
+                                                 LOCK_DIE_ON_ERROR);
                else
-                       state->newfd = hold_locked_index(state->lock_file, LOCK_DIE_ON_ERROR);
+                       repo_hold_locked_index(state->repo, &state->lock_file,
+                                              LOCK_DIE_ON_ERROR);
        }
 
        if (state->check_index && read_apply_cache(state) < 0) {
@@ -4751,6 +4788,8 @@ static int apply_patch(struct apply_state *state,
        if (state->summary && state->apply_verbosity > verbosity_silent)
                summary_patch_list(list);
 
+       if (flush_attributes)
+               reset_parsed_attributes();
 end:
        free_patch_list(list);
        strbuf_release(&buf);
@@ -4762,6 +4801,9 @@ static int apply_option_parse_exclude(const struct option *opt,
                                      const char *arg, int unset)
 {
        struct apply_state *state = opt->value;
+
+       BUG_ON_OPT_NEG(unset);
+
        add_name_limit(state, arg, 1);
        return 0;
 }
@@ -4770,6 +4812,9 @@ static int apply_option_parse_include(const struct option *opt,
                                      const char *arg, int unset)
 {
        struct apply_state *state = opt->value;
+
+       BUG_ON_OPT_NEG(unset);
+
        add_name_limit(state, arg, 0);
        state->has_include = 1;
        return 0;
@@ -4780,6 +4825,9 @@ static int apply_option_parse_p(const struct option *opt,
                                int unset)
 {
        struct apply_state *state = opt->value;
+
+       BUG_ON_OPT_NEG(unset);
+
        state->p_value = atoi(arg);
        state->p_value_known = 1;
        return 0;
@@ -4789,6 +4837,9 @@ static int apply_option_parse_space_change(const struct option *opt,
                                           const char *arg, int unset)
 {
        struct apply_state *state = opt->value;
+
+       BUG_ON_OPT_ARG(arg);
+
        if (unset)
                state->ws_ignore_action = ignore_ws_none;
        else
@@ -4800,9 +4851,12 @@ static int apply_option_parse_whitespace(const struct option *opt,
                                         const char *arg, int unset)
 {
        struct apply_state *state = opt->value;
+
+       BUG_ON_OPT_NEG(unset);
+
        state->whitespace_option = arg;
        if (parse_whitespace_option(state, arg))
-               exit(1);
+               return -1;
        return 0;
 }
 
@@ -4810,6 +4864,9 @@ static int apply_option_parse_directory(const struct option *opt,
                                        const char *arg, int unset)
 {
        struct apply_state *state = opt->value;
+
+       BUG_ON_OPT_NEG(unset);
+
        strbuf_reset(&state->root);
        strbuf_addstr(&state->root, arg);
        strbuf_complete(&state->root, '/');
@@ -4898,22 +4955,18 @@ int apply_all_patches(struct apply_state *state,
        }
 
        if (state->update_index) {
-               res = write_locked_index(&the_index, state->lock_file, COMMIT_LOCK);
+               res = write_locked_index(state->repo->index, &state->lock_file, COMMIT_LOCK);
                if (res) {
                        error(_("Unable to write new index file"));
                        res = -128;
                        goto end;
                }
-               state->newfd = -1;
        }
 
        res = !!errs;
 
 end:
-       if (state->newfd >= 0) {
-               rollback_lock_file(state->lock_file);
-               state->newfd = -1;
-       }
+       rollback_lock_file(&state->lock_file);
 
        if (state->apply_verbosity <= verbosity_silent) {
                set_error_routine(state->saved_error_routine);
@@ -4931,15 +4984,15 @@ int apply_parse_options(int argc, const char **argv,
                        const char * const *apply_usage)
 {
        struct option builtin_apply_options[] = {
-               { OPTION_CALLBACK, 0, "exclude", state, N_("path"),
+               OPT_CALLBACK_F(0, "exclude", state, N_("path"),
                        N_("don't apply changes matching the given path"),
-                       0, apply_option_parse_exclude },
-               { OPTION_CALLBACK, 0, "include", state, N_("path"),
+                       PARSE_OPT_NONEG, apply_option_parse_exclude),
+               OPT_CALLBACK_F(0, "include", state, N_("path"),
                        N_("apply changes matching the given path"),
-                       0, apply_option_parse_include },
-               { OPTION_CALLBACK, 'p', NULL, state, N_("num"),
+                       PARSE_OPT_NONEG, apply_option_parse_include),
+               OPT_CALLBACK('p', NULL, state, N_("num"),
                        N_("remove <num> leading slashes from traditional diff paths"),
-                       0, apply_option_parse_p },
+                       apply_option_parse_p),
                OPT_BOOL(0, "no-add", &state->no_add,
                        N_("ignore additions made by the patch")),
                OPT_BOOL(0, "stat", &state->diffstat,
@@ -4954,10 +5007,13 @@ int apply_parse_options(int argc, const char **argv,
                        N_("instead of applying the patch, see if the patch is applicable")),
                OPT_BOOL(0, "index", &state->check_index,
                        N_("make sure the patch is applicable to the current index")),
+               OPT_BOOL('N', "intent-to-add", &state->ita_only,
+                       N_("mark new files with `git add --intent-to-add`")),
                OPT_BOOL(0, "cached", &state->cached,
                        N_("apply a patch without touching the working tree")),
-               OPT_BOOL(0, "unsafe-paths", &state->unsafe_paths,
-                       N_("accept a patch that touches outside the working area")),
+               OPT_BOOL_F(0, "unsafe-paths", &state->unsafe_paths,
+                          N_("accept a patch that touches outside the working area"),
+                          PARSE_OPT_NOCOMPLETE),
                OPT_BOOL(0, "apply", force_apply,
                        N_("also apply the patch (use with --stat/--summary/--check)")),
                OPT_BOOL('3', "3way", &state->threeway,
@@ -4969,15 +5025,15 @@ int apply_parse_options(int argc, const char **argv,
                        N_("paths are separated with NUL character"), '\0'),
                OPT_INTEGER('C', NULL, &state->p_context,
                                N_("ensure at least <n> lines of context match")),
-               { OPTION_CALLBACK, 0, "whitespace", state, N_("action"),
+               OPT_CALLBACK(0, "whitespace", state, N_("action"),
                        N_("detect new or modified lines that have whitespace errors"),
-                       0, apply_option_parse_whitespace },
-               { OPTION_CALLBACK, 0, "ignore-space-change", state, NULL,
+                       apply_option_parse_whitespace),
+               OPT_CALLBACK_F(0, "ignore-space-change", state, NULL,
                        N_("ignore changes in whitespace when finding context"),
-                       PARSE_OPT_NOARG, apply_option_parse_space_change },
-               { OPTION_CALLBACK, 0, "ignore-whitespace", state, NULL,
+                       PARSE_OPT_NOARG, apply_option_parse_space_change),
+               OPT_CALLBACK_F(0, "ignore-whitespace", state, NULL,
                        N_("ignore changes in whitespace when finding context"),
-                       PARSE_OPT_NOARG, apply_option_parse_space_change },
+                       PARSE_OPT_NOARG, apply_option_parse_space_change),
                OPT_BOOL('R', "reverse", &state->apply_in_reverse,
                        N_("apply the patch in reverse")),
                OPT_BOOL(0, "unidiff-zero", &state->unidiff_zero,
@@ -4993,9 +5049,9 @@ int apply_parse_options(int argc, const char **argv,
                OPT_BIT(0, "recount", options,
                        N_("do not trust the line counts in the hunk headers"),
                        APPLY_OPT_RECOUNT),
-               { OPTION_CALLBACK, 0, "directory", state, N_("root"),
+               OPT_CALLBACK(0, "directory", state, N_("root"),
                        N_("prepend <root> to all filenames"),
-                       0, apply_option_parse_directory },
+                       apply_option_parse_directory),
                OPT_END()
        };