Merge branch 'jc/apply-beyond-symlink'
[gitweb.git] / builtin / apply.c
index c2c6fda08c561f0b1b72aae7b252bc50ed211ae9..525db4a2a237fa0b12a254fd72b86dcd66738e93 100644 (file)
@@ -7,6 +7,7 @@
  *
  */
 #include "cache.h"
+#include "lockfile.h"
 #include "cache-tree.h"
 #include "quote.h"
 #include "blob.h"
@@ -55,7 +56,7 @@ static const char *fake_ancestor;
 static int line_termination = '\n';
 static unsigned int p_context = UINT_MAX;
 static const char * const apply_usage[] = {
-       N_("git apply [options] [<patch>...]"),
+       N_("git apply [<options>] [<patch>...]"),
        NULL
 };
 
@@ -301,11 +302,13 @@ static int fuzzy_matchlines(const char *s1, size_t n1,
        while ((*last2 == '\r') || (*last2 == '\n'))
                last2--;
 
-       /* skip leading whitespace */
-       while (isspace(*s1) && (s1 <= last1))
-               s1++;
-       while (isspace(*s2) && (s2 <= last2))
-               s2++;
+       /* 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;
@@ -434,7 +437,7 @@ static unsigned long linelen(const char *buffer, unsigned long size)
 
 static int is_dev_null(const char *str)
 {
-       return !memcmp("/dev/null", str, 9) && isspace(str[9]);
+       return skip_prefix(str, "/dev/null", &str) && isspace(*str);
 }
 
 #define TERM_SPACE     1
@@ -655,11 +658,6 @@ static size_t diff_timestamp_len(const char *line, size_t len)
        return line + len - end;
 }
 
-static char *null_strdup(const char *s)
-{
-       return s ? xstrdup(s) : NULL;
-}
-
 static char *find_name_common(const char *line, const char *def,
                              int p_value, const char *end, int terminate)
 {
@@ -682,10 +680,10 @@ static char *find_name_common(const char *line, const char *def,
                        start = line;
        }
        if (!start)
-               return squash_slash(null_strdup(def));
+               return squash_slash(xstrdup_or_null(def));
        len = line - start;
        if (!len)
-               return squash_slash(null_strdup(def));
+               return squash_slash(xstrdup_or_null(def));
 
        /*
         * Generally we prefer the shorter name, especially
@@ -907,7 +905,7 @@ static void parse_traditional_patch(const char *first, const char *second, struc
                        patch->old_name = name;
                } else {
                        patch->old_name = name;
-                       patch->new_name = null_strdup(name);
+                       patch->new_name = xstrdup_or_null(name);
                }
        }
        if (!name)
@@ -996,7 +994,7 @@ static int gitdiff_delete(const char *line, struct patch *patch)
 {
        patch->is_delete = 1;
        free(patch->old_name);
-       patch->old_name = null_strdup(patch->def_name);
+       patch->old_name = xstrdup_or_null(patch->def_name);
        return gitdiff_oldmode(line, patch);
 }
 
@@ -1004,7 +1002,7 @@ static int gitdiff_newfile(const char *line, struct patch *patch)
 {
        patch->is_new = 1;
        free(patch->new_name);
-       patch->new_name = null_strdup(patch->def_name);
+       patch->new_name = xstrdup_or_null(patch->def_name);
        return gitdiff_newmode(line, patch);
 }
 
@@ -1074,7 +1072,7 @@ static int gitdiff_index(const char *line, struct patch *patch)
 
        line = ptr + 2;
        ptr = strchr(line, ' ');
-       eol = strchr(line, '\n');
+       eol = strchrnul(line, '\n');
 
        if (!ptr || eol < ptr)
                ptr = eol;
@@ -1280,9 +1278,7 @@ static int parse_git_header(const char *line, int len, unsigned int size, struct
         */
        patch->def_name = git_header_name(line, len);
        if (patch->def_name && root) {
-               char *s = xmalloc(root_len + strlen(patch->def_name) + 1);
-               strcpy(s, root);
-               strcpy(s + root_len, patch->def_name);
+               char *s = xstrfmt("%s%s", root, patch->def_name);
                free(patch->def_name);
                patch->def_name = s;
        }
@@ -1410,10 +1406,10 @@ static void recount_diff(const char *line, int size, struct fragment *fragment)
                case '\\':
                        continue;
                case '@':
-                       ret = size < 3 || prefixcmp(line, "@@ ");
+                       ret = size < 3 || !starts_with(line, "@@ ");
                        break;
                case 'd':
-                       ret = size < 5 || prefixcmp(line, "diff ");
+                       ret = size < 5 || !starts_with(line, "diff ");
                        break;
                default:
                        ret = -1;
@@ -1799,11 +1795,11 @@ static struct fragment *parse_binary_hunk(char **buf_p,
 
        *status_p = 0;
 
-       if (!prefixcmp(buffer, "delta ")) {
+       if (starts_with(buffer, "delta ")) {
                patch_method = BINARY_DELTA_DEFLATED;
                origlen = strtoul(buffer + 6, NULL, 10);
        }
-       else if (!prefixcmp(buffer, "literal ")) {
+       else if (starts_with(buffer, "literal ")) {
                patch_method = BINARY_LITERAL_DEFLATED;
                origlen = strtoul(buffer + 8, NULL, 10);
        }
@@ -1921,6 +1917,66 @@ static int parse_binary(char *buffer, unsigned long size, struct patch *patch)
        return used;
 }
 
+static void prefix_one(char **name)
+{
+       char *old_name = *name;
+       if (!old_name)
+               return;
+       *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
+       free(old_name);
+}
+
+static void prefix_patch(struct patch *p)
+{
+       if (!prefix || p->is_toplevel_relative)
+               return;
+       prefix_one(&p->new_name);
+       prefix_one(&p->old_name);
+}
+
+/*
+ * include/exclude
+ */
+
+static struct string_list limit_by_name;
+static int has_include;
+static void add_name_limit(const char *name, int exclude)
+{
+       struct string_list_item *it;
+
+       it = string_list_append(&limit_by_name, name);
+       it->util = exclude ? NULL : (void *) 1;
+}
+
+static int use_patch(struct patch *p)
+{
+       const char *pathname = p->new_name ? p->new_name : p->old_name;
+       int i;
+
+       /* Paths outside are not touched regardless of "--include" */
+       if (0 < prefix_length) {
+               int pathlen = strlen(pathname);
+               if (pathlen <= prefix_length ||
+                   memcmp(prefix, pathname, prefix_length))
+                       return 0;
+       }
+
+       /* See if it matches any of exclude/include rule */
+       for (i = 0; i < limit_by_name.nr; i++) {
+               struct string_list_item *it = &limit_by_name.items[i];
+               if (!wildmatch(it->string, pathname, 0, NULL))
+                       return (it->util != NULL);
+       }
+
+       /*
+        * If we had any include, a path that does not match any rule is
+        * not used.  Otherwise, we saw bunch of exclude rules (or none)
+        * and such a path is used.
+        */
+       return !has_include;
+}
+
+
 /*
  * Read the patch text in "buffer" that extends for "size" bytes; stop
  * reading after seeing a single patch (i.e. changes to a single file).
@@ -1936,21 +1992,20 @@ static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
        if (offset < 0)
                return offset;
 
-       patch->ws_rule = whitespace_rule(patch->new_name
-                                        ? patch->new_name
-                                        : patch->old_name);
+       prefix_patch(patch);
+
+       if (!use_patch(patch))
+               patch->ws_rule = 0;
+       else
+               patch->ws_rule = whitespace_rule(patch->new_name
+                                                ? patch->new_name
+                                                : patch->old_name);
 
        patchsize = parse_single_patch(buffer + offset + hdrsize,
                                       size - offset - hdrsize, patch);
 
        if (!patchsize) {
-               static const char *binhdr[] = {
-                       "Binary files ",
-                       "Files ",
-                       NULL,
-               };
                static const char git_binary[] = "GIT binary patch\n";
-               int i;
                int hd = hdrsize + offset;
                unsigned long llen = linelen(buffer + hd, size - hd);
 
@@ -1966,6 +2021,12 @@ static int parse_chunk(char *buffer, unsigned long size, struct patch *patch)
                                patchsize = 0;
                }
                else if (!memcmp(" differ\n", buffer + hd + llen - 8, 8)) {
+                       static const char *binhdr[] = {
+                               "Binary files ",
+                               "Files ",
+                               NULL,
+                       };
+                       int i;
                        for (i = 0; binhdr[i]; i++) {
                                int len = strlen(binhdr[i]);
                                if (len < size - hd &&
@@ -2170,6 +2231,12 @@ static void update_pre_post_images(struct image *preimage,
                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));
+
        /* Fix the length of the whole thing */
        postimage->len = new - postimage->buf;
        postimage->nr -= reduced;
@@ -2325,10 +2392,27 @@ static int match_fragment(struct image *img,
 
        /*
         * The hunk does not apply byte-by-byte, but the hash says
-        * it might with whitespace fuzz. We haven't been asked to
+        * it might with whitespace fuzz. We weren't asked to
         * ignore whitespace, we were asked to correct whitespace
         * errors, so let's try matching after whitespace correction.
         *
+        * While checking the preimage against the target, whitespace
+        * errors in both fixed, we count how large the corresponding
+        * postimage needs to be.  The postimage prepared by
+        * apply_one_fragment() has whitespace errors fixed on added
+        * lines already, but the common lines were propagated as-is,
+        * which may become longer when their whitespace errors are
+        * fixed.
+        */
+
+       /* First count added lines in postimage */
+       postlen = 0;
+       for (i = 0; i < postimage->nr; i++) {
+               if (!(postimage->line[i].flag & LINE_COMMON))
+                       postlen += postimage->line[i].len;
+       }
+
+       /*
         * The preimage may extend beyond the end of the file,
         * but in this loop we will only handle the part of the
         * preimage that falls within the file.
@@ -2336,7 +2420,6 @@ static int match_fragment(struct image *img,
        strbuf_init(&fixed, preimage->len + 1);
        orig = preimage->buf;
        target = img->buf + try;
-       postlen = 0;
        for (i = 0; i < preimage_limit; i++) {
                size_t oldlen = preimage->line[i].len;
                size_t tgtlen = img->line[try_lno + i].len;
@@ -2364,7 +2447,10 @@ static int match_fragment(struct image *img,
                match = (tgtfix.len == fixed.len - fixstart &&
                         !memcmp(tgtfix.buf, fixed.buf + fixstart,
                                             fixed.len - fixstart));
-               postlen += tgtfix.len;
+
+               /* Add the length if this is common with the postimage */
+               if (preimage->line[i].flag & LINE_COMMON)
+                       postlen += tgtfix.len;
 
                strbuf_release(&tgtfix);
                if (!match)
@@ -2562,7 +2648,7 @@ static void update_image(struct image *img,
                 * NOTE: this knows that we never call remove_first_line()
                 * on anything other than pre/post image.
                 */
-               img->line = xrealloc(img->line, nr * sizeof(*img->line));
+               REALLOC_ARRAY(img->line, nr);
                img->line_allocated = img->line;
        }
        if (preimage_limit != postimage->nr)
@@ -2868,9 +2954,7 @@ static int apply_binary_fragment(struct image *img, struct patch *patch)
        case BINARY_LITERAL_DEFLATED:
                clear_image(img);
                img->len = fragment->size;
-               img->buf = xmalloc(img->len+1);
-               memcpy(img->buf, fragment->patch, img->len);
-               img->buf[img->len] = '\0';
+               img->buf = xmemdupz(fragment->patch, img->len);
                return 0;
        }
        return -1;
@@ -3085,13 +3169,15 @@ static void prepare_fn_table(struct patch *patch)
        }
 }
 
-static int checkout_target(struct cache_entry *ce, struct stat *st)
+static int checkout_target(struct index_state *istate,
+                          struct cache_entry *ce, struct stat *st)
 {
        struct checkout costate;
 
        memset(&costate, 0, sizeof(costate));
        costate.base_dir = "";
        costate.refresh_cache = 1;
+       costate.istate = istate;
        if (checkout_entry(ce, &costate, NULL) || lstat(ce->name, st))
                return error(_("cannot checkout %s"), ce->name);
        return 0;
@@ -3260,7 +3346,7 @@ static int load_current(struct image *image, struct patch *patch)
        if (lstat(name, &st)) {
                if (errno != ENOENT)
                        return error(_("%s: %s"), name, strerror(errno));
-               if (checkout_target(ce, &st))
+               if (checkout_target(&the_index, ce, &st))
                        return -1;
        }
        if (verify_index_match(ce, &st))
@@ -3414,7 +3500,7 @@ static int check_preimage(struct patch *patch, struct cache_entry **ce, struct s
                }
                *ce = active_cache[pos];
                if (stat_ret < 0) {
-                       if (checkout_target(*ce, st))
+                       if (checkout_target(&the_index, *ce, st))
                                return -1;
                }
                if (!cached && verify_index_match(*ce, st))
@@ -3762,12 +3848,12 @@ static int preimage_sha1_in_gitlink_patch(struct patch *p, unsigned char sha1[20
            hunk->oldpos == 1 && hunk->oldlines == 1 &&
            /* does preimage begin with the heading? */
            (preimage = memchr(hunk->patch, '\n', hunk->size)) != NULL &&
-           !prefixcmp(++preimage, heading) &&
+           starts_with(++preimage, heading) &&
            /* does it record full SHA-1? */
            !get_sha1_hex(preimage + sizeof(heading) - 1, sha1) &&
            preimage[sizeof(heading) + 40 - 1] == '\n' &&
            /* does the abbreviated name on the index line agree with it? */
-           !prefixcmp(preimage + sizeof(heading) - 1, p->old_sha1_prefix))
+           starts_with(preimage + sizeof(heading) - 1, p->old_sha1_prefix))
                return 0; /* it all looks fine */
 
        /* we may have full object name on the index line */
@@ -3779,7 +3865,7 @@ static void build_fake_ancestor(struct patch *list, const char *filename)
 {
        struct patch *patch;
        struct index_state result = { NULL };
-       int fd;
+       static struct lock_file lock;
 
        /* Once we start supporting the reverse patch, it may be
         * worth showing the new sha1 prefix, but until then...
@@ -3797,7 +3883,7 @@ static void build_fake_ancestor(struct patch *list, const char *filename)
                        if (!preimage_sha1_in_gitlink_patch(patch, sha1))
                                ; /* ok, the textual part looks sane */
                        else
-                               die("sha1 information is lacking or useless for submoule %s",
+                               die("sha1 information is lacking or useless for submodule %s",
                                    name);
                } else if (!get_sha1_blob(patch->old_sha1_prefix, sha1)) {
                        ; /* ok */
@@ -3817,8 +3903,8 @@ static void build_fake_ancestor(struct patch *list, const char *filename)
                        die ("Could not add %s to temporary index", name);
        }
 
-       fd = open(filename, O_WRONLY | O_CREAT, 0666);
-       if (fd < 0 || write_index(&result, fd) || close(fd))
+       hold_lock_file_for_update(&lock, filename, LOCK_DIE_ON_ERROR);
+       if (write_locked_index(&result, &lock, COMMIT_LOCK))
                die ("Could not write temporary index to %s", filename);
 
        discard_index(&result);
@@ -3980,9 +4066,10 @@ static void add_index_file(const char *path, unsigned mode, void *buf, unsigned
        ce->ce_flags = create_ce_flags(0);
        ce->ce_namelen = namelen;
        if (S_ISGITLINK(mode)) {
-               const char *s = buf;
+               const char *s;
 
-               if (get_sha1_hex(s + strlen("Subproject commit "), ce->sha1))
+               if (!skip_prefix(buf, "Subproject commit ", &s) ||
+                   get_sha1_hex(s, ce->sha1))
                        die(_("corrupt patch for submodule %s"), path);
        } else {
                if (!cached) {
@@ -4196,7 +4283,7 @@ static int write_out_one_reject(struct patch *patch)
                return error(_("cannot open %s: %s"), namebuf, strerror(errno));
 
        /* Normal git tools never deal with .rej, so do not pretend
-        * this is a git patch by saying --git nor give extended
+        * this is a git patch by saying --git or giving extended
         * headers.  While at it, maybe please "kompare" that wants
         * the trailing TAB and some garbage at the end of line ;-).
         */
@@ -4248,7 +4335,7 @@ static int write_out_results(struct patch *list)
        if (cpath.nr) {
                struct string_list_item *item;
 
-               sort_string_list(&cpath);
+               string_list_sort(&cpath);
                for_each_string_list_item(item, &cpath)
                        fprintf(stderr, "U %s\n", item->string);
                string_list_clear(&cpath, 0);
@@ -4261,64 +4348,6 @@ static int write_out_results(struct patch *list)
 
 static struct lock_file lock_file;
 
-static struct string_list limit_by_name;
-static int has_include;
-static void add_name_limit(const char *name, int exclude)
-{
-       struct string_list_item *it;
-
-       it = string_list_append(&limit_by_name, name);
-       it->util = exclude ? NULL : (void *) 1;
-}
-
-static int use_patch(struct patch *p)
-{
-       const char *pathname = p->new_name ? p->new_name : p->old_name;
-       int i;
-
-       /* Paths outside are not touched regardless of "--include" */
-       if (0 < prefix_length) {
-               int pathlen = strlen(pathname);
-               if (pathlen <= prefix_length ||
-                   memcmp(prefix, pathname, prefix_length))
-                       return 0;
-       }
-
-       /* See if it matches any of exclude/include rule */
-       for (i = 0; i < limit_by_name.nr; i++) {
-               struct string_list_item *it = &limit_by_name.items[i];
-               if (!fnmatch(it->string, pathname, 0))
-                       return (it->util != NULL);
-       }
-
-       /*
-        * If we had any include, a path that does not match any rule is
-        * not used.  Otherwise, we saw bunch of exclude rules (or none)
-        * and such a path is used.
-        */
-       return !has_include;
-}
-
-
-static void prefix_one(char **name)
-{
-       char *old_name = *name;
-       if (!old_name)
-               return;
-       *name = xstrdup(prefix_filename(prefix, prefix_length, *name));
-       free(old_name);
-}
-
-static void prefix_patches(struct patch *p)
-{
-       if (!prefix || p->is_toplevel_relative)
-               return;
-       for ( ; p; p = p->next) {
-               prefix_one(&p->new_name);
-               prefix_one(&p->old_name);
-       }
-}
-
 #define INACCURATE_EOF (1<<0)
 #define RECOUNT                (1<<1)
 
@@ -4344,8 +4373,6 @@ static int apply_patch(int fd, const char *filename, int options)
                        break;
                if (apply_in_reverse)
                        reverse_patches(patch);
-               if (prefix)
-                       prefix_patches(patch);
                if (use_patch(patch)) {
                        patch_stats(patch);
                        *listp = patch;
@@ -4403,13 +4430,11 @@ static int apply_patch(int fd, const char *filename, int options)
        return 0;
 }
 
-static int git_apply_config(const char *var, const char *value, void *cb)
+static void git_apply_config(void)
 {
-       if (!strcmp(var, "apply.whitespace"))
-               return git_config_string(&apply_default_whitespace, var, value);
-       else if (!strcmp(var, "apply.ignorewhitespace"))
-               return git_config_string(&apply_default_ignorewhitespace, var, value);
-       return git_default_config(var, value, cb);
+       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);
 }
 
 static int option_parse_exclude(const struct option *opt,
@@ -4559,7 +4584,7 @@ int cmd_apply(int argc, const char **argv, const char *prefix_)
 
        prefix = prefix_;
        prefix_length = prefix ? strlen(prefix) : 0;
-       git_config(git_apply_config, NULL);
+       git_apply_config();
        if (apply_default_whitespace)
                parse_whitespace_option(apply_default_whitespace);
        if (apply_default_ignorewhitespace)
@@ -4641,8 +4666,7 @@ int cmd_apply(int argc, const char **argv, const char *prefix_)
        }
 
        if (update_index) {
-               if (write_cache(newfd, active_cache, active_nr) ||
-                   commit_locked_index(&lock_file))
+               if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
                        die(_("Unable to write new index file"));
        }