]> git.proxmox.com Git - libgit2.git/blobdiff - src/stash.c
New upstream version 1.3.0+dfsg.1
[libgit2.git] / src / stash.c
index a316d18c25c3e37535fd5b8a7efbd5f661e41a4d..49ea26fdd529243aa3da6224ab6b641b5ab808d4 100644 (file)
@@ -6,11 +6,13 @@
  */
 
 #include "common.h"
+
 #include "repository.h"
 #include "commit.h"
 #include "message.h"
 #include "tree.h"
 #include "reflog.h"
+#include "blob.h"
 #include "git2/diff.h"
 #include "git2/stash.h"
 #include "git2/status.h"
 #include "git2/index.h"
 #include "git2/transaction.h"
 #include "git2/merge.h"
+#include "index.h"
 #include "signature.h"
+#include "iterator.h"
+#include "merge.h"
+#include "diff.h"
+#include "diff_generate.h"
 
 static int create_error(int error, const char *msg)
 {
-       giterr_set(GITERR_STASH, "Cannot stash changes - %s", msg);
+       git_error_set(GIT_ERROR_STASH, "cannot stash changes - %s", msg);
        return error;
 }
 
@@ -31,7 +38,7 @@ static int retrieve_head(git_reference **out, git_repository *repo)
        int error = git_repository_head(out, repo);
 
        if (error == GIT_EUNBORNBRANCH)
-               return create_error(error, "You do not have the initial commit yet.");
+               return create_error(error, "you do not have the initial commit yet.");
 
        return error;
 }
@@ -41,7 +48,7 @@ static int append_abbreviated_oid(git_buf *out, const git_oid *b_commit)
        char *formatted_oid;
 
        formatted_oid = git_oid_allocfmt(b_commit);
-       GITERR_CHECK_ALLOC(formatted_oid);
+       GIT_ERROR_CHECK_ALLOC(formatted_oid);
 
        git_buf_put(out, formatted_oid, 7);
        git__free(formatted_oid);
@@ -49,10 +56,10 @@ static int append_abbreviated_oid(git_buf *out, const git_oid *b_commit)
        return git_buf_oom(out) ? -1 : 0;
 }
 
-static int append_commit_description(git_buf *out, git_commitcommit)
+static int append_commit_description(git_buf *out, git_commit *commit)
 {
        const char *summary = git_commit_summary(commit);
-       GITERR_CHECK_ALLOC(summary);
+       GIT_ERROR_CHECK_ALLOC(summary);
 
        if (append_abbreviated_oid(out, git_commit_id(commit)) < 0)
                return -1;
@@ -97,19 +104,23 @@ cleanup:
        return error;
 }
 
-static int build_tree_from_index(git_tree **out, git_index *index)
+static int build_tree_from_index(
+       git_tree **out,
+       git_repository *repo,
+       git_index *index)
 {
        int error;
        git_oid i_tree_oid;
 
-       if ((error = git_index_write_tree(&i_tree_oid, index)) < 0)
-               return -1;
+       if ((error = git_index_write_tree_to(&i_tree_oid, index, repo)) < 0)
+               return error;
 
-       return git_tree_lookup(out, git_index_owner(index), &i_tree_oid);
+       return git_tree_lookup(out, repo, &i_tree_oid);
 }
 
 static int commit_index(
        git_commit **i_commit,
+       git_repository *repo,
        git_index *index,
        const git_signature *stasher,
        const char *message,
@@ -120,7 +131,7 @@ static int commit_index(
        git_buf msg = GIT_BUF_INIT;
        int error;
 
-       if ((error = build_tree_from_index(&i_tree, index)) < 0)
+       if ((error = build_tree_from_index(&i_tree, repo, index)) < 0)
                goto cleanup;
 
        if ((error = git_buf_printf(&msg, "index on %s\n", message)) < 0)
@@ -143,7 +154,7 @@ static int commit_index(
 
 cleanup:
        git_tree_free(i_tree);
-       git_buf_free(&msg);
+       git_buf_dispose(&msg);
        return error;
 }
 
@@ -153,7 +164,38 @@ struct stash_update_rules {
        bool include_ignored;
 };
 
+/*
+ * Similar to git_index_add_bypath but able to operate on any
+ * index without making assumptions about the repository's index
+ */
+static int stash_to_index(
+       git_repository *repo,
+       git_index *index,
+       const char *path)
+{
+       git_index *repo_index = NULL;
+       git_index_entry entry = {{0}};
+       struct stat st;
+       int error;
+
+       if (!git_repository_is_bare(repo) &&
+           (error = git_repository_index__weakptr(&repo_index, repo)) < 0)
+               return error;
+
+       if ((error = git_blob__create_from_paths(
+           &entry.id, &st, repo, NULL, path, 0, true)) < 0)
+               return error;
+
+       git_index_entry__init_from_stat(&entry, &st,
+               (repo_index == NULL || !repo_index->distrust_filemode));
+
+       entry.path = path;
+
+       return git_index_add(index, &entry);
+}
+
 static int stash_update_index_from_diff(
+       git_repository *repo,
        git_index *index,
        const git_diff *diff,
        struct stash_update_rules *data)
@@ -191,15 +233,15 @@ static int stash_update_index_from_diff(
 
                default:
                        /* Unimplemented */
-                       giterr_set(
-                               GITERR_INVALID,
-                               "Cannot update index. Unimplemented status (%d)",
+                       git_error_set(
+                               GIT_ERROR_INVALID,
+                               "cannot update index. Unimplemented status (%d)",
                                delta->status);
                        return -1;
                }
 
                if (add_path != NULL)
-                       error = git_index_add_bypath(index, add_path);
+                       error = stash_to_index(repo, index, add_path);
        }
 
        return error;
@@ -207,17 +249,19 @@ static int stash_update_index_from_diff(
 
 static int build_untracked_tree(
        git_tree **tree_out,
-       git_index *index,
+       git_repository *repo,
        git_commit *i_commit,
        uint32_t flags)
 {
+       git_index *i_index = NULL;
        git_tree *i_tree = NULL;
        git_diff *diff = NULL;
        git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
        struct stash_update_rules data = {0};
        int error;
 
-       git_index_clear(index);
+       if ((error = git_index_new(&i_index)) < 0)
+               goto cleanup;
 
        if (flags & GIT_STASH_INCLUDE_UNTRACKED) {
                opts.flags |= GIT_DIFF_INCLUDE_UNTRACKED |
@@ -234,24 +278,24 @@ static int build_untracked_tree(
        if ((error = git_commit_tree(&i_tree, i_commit)) < 0)
                goto cleanup;
 
-       if ((error = git_diff_tree_to_workdir(
-                       &diff, git_index_owner(index), i_tree, &opts)) < 0)
+       if ((error = git_diff_tree_to_workdir(&diff, repo, i_tree, &opts)) < 0)
                goto cleanup;
 
-       if ((error = stash_update_index_from_diff(index, diff, &data)) < 0)
+       if ((error = stash_update_index_from_diff(repo, i_index, diff, &data)) < 0)
                goto cleanup;
 
-       error = build_tree_from_index(tree_out, index);
+       error = build_tree_from_index(tree_out, repo, i_index);
 
 cleanup:
        git_diff_free(diff);
        git_tree_free(i_tree);
+       git_index_free(i_index);
        return error;
 }
 
 static int commit_untracked(
        git_commit **u_commit,
-       git_index *index,
+       git_repository *repo,
        const git_signature *stasher,
        const char *message,
        git_commit *i_commit,
@@ -262,7 +306,7 @@ static int commit_untracked(
        git_buf msg = GIT_BUF_INIT;
        int error;
 
-       if ((error = build_untracked_tree(&u_tree, index, i_commit, flags)) < 0)
+       if ((error = build_untracked_tree(&u_tree, repo, i_commit, flags)) < 0)
                goto cleanup;
 
        if ((error = git_buf_printf(&msg, "untracked files on %s\n", message)) < 0)
@@ -270,7 +314,7 @@ static int commit_untracked(
 
        if ((error = git_commit_create(
                &u_commit_oid,
-               git_index_owner(index),
+               repo,
                NULL,
                stasher,
                stasher,
@@ -281,42 +325,64 @@ static int commit_untracked(
                NULL)) < 0)
                goto cleanup;
 
-       error = git_commit_lookup(u_commit, git_index_owner(index), &u_commit_oid);
+       error = git_commit_lookup(u_commit, repo, &u_commit_oid);
 
 cleanup:
        git_tree_free(u_tree);
-       git_buf_free(&msg);
+       git_buf_dispose(&msg);
        return error;
 }
 
+static git_diff_delta *stash_delta_merge(
+       const git_diff_delta *a,
+       const git_diff_delta *b,
+       git_pool *pool)
+{
+       /* Special case for stash: if a file is deleted in the index, but exists
+        * in the working tree, we need to stash the workdir copy for the workdir.
+        */
+       if (a->status == GIT_DELTA_DELETED && b->status == GIT_DELTA_UNTRACKED) {
+               git_diff_delta *dup = git_diff__delta_dup(b, pool);
+
+               if (dup)
+                       dup->status = GIT_DELTA_MODIFIED;
+               return dup;
+       }
+
+       return git_diff__merge_like_cgit(a, b, pool);
+}
+
 static int build_workdir_tree(
        git_tree **tree_out,
-       git_index *index,
+       git_repository *repo,
+       git_index *i_index,
        git_commit *b_commit)
 {
-       git_repository *repo = git_index_owner(index);
        git_tree *b_tree = NULL;
-       git_diff *diff = NULL;
+       git_diff *diff = NULL, *idx_to_wd = NULL;
        git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
        struct stash_update_rules data = {0};
        int error;
 
-       opts.flags = GIT_DIFF_IGNORE_SUBMODULES;
+       opts.flags = GIT_DIFF_IGNORE_SUBMODULES | GIT_DIFF_INCLUDE_UNTRACKED;
 
        if ((error = git_commit_tree(&b_tree, b_commit)) < 0)
                goto cleanup;
 
-       if ((error = git_diff_tree_to_workdir(&diff, repo, b_tree, &opts)) < 0)
+       if ((error = git_diff_tree_to_index(&diff, repo, b_tree, i_index, &opts)) < 0 ||
+               (error = git_diff_index_to_workdir(&idx_to_wd, repo, i_index, &opts)) < 0 ||
+               (error = git_diff__merge(diff, idx_to_wd, stash_delta_merge)) < 0)
                goto cleanup;
 
        data.include_changed = true;
 
-       if ((error = stash_update_index_from_diff(index, diff, &data)) < 0)
+       if ((error = stash_update_index_from_diff(repo, i_index, diff, &data)) < 0)
                goto cleanup;
 
-       error = build_tree_from_index(tree_out, index);
+       error = build_tree_from_index(tree_out, repo, i_index);
 
 cleanup:
+       git_diff_free(idx_to_wd);
        git_diff_free(diff);
        git_tree_free(b_tree);
 
@@ -325,33 +391,36 @@ cleanup:
 
 static int commit_worktree(
        git_oid *w_commit_oid,
-       git_index *index,
+       git_repository *repo,
        const git_signature *stasher,
        const char *message,
        git_commit *i_commit,
        git_commit *b_commit,
        git_commit *u_commit)
 {
-       int error = 0;
-       git_tree *w_tree = NULL, *i_tree = NULL;
-       const git_commit *parents[] = { NULL, NULL,     NULL };
+       const git_commit *parents[] = { NULL, NULL, NULL };
+       git_index *i_index = NULL, *r_index = NULL;
+       git_tree *w_tree = NULL;
+       int error = 0, ignorecase;
 
        parents[0] = b_commit;
        parents[1] = i_commit;
        parents[2] = u_commit;
 
-       if ((error = git_commit_tree(&i_tree, i_commit)) < 0)
+       if ((error = git_repository_index(&r_index, repo) < 0) ||
+           (error = git_index_new(&i_index)) < 0 ||
+           (error = git_index__fill(i_index, &r_index->entries) < 0) ||
+           (error = git_repository__configmap_lookup(&ignorecase, repo, GIT_CONFIGMAP_IGNORECASE)) < 0)
                goto cleanup;
 
-       if ((error = git_index_read_tree(index, i_tree)) < 0)
-               goto cleanup;
+       git_index__set_ignore_case(i_index, ignorecase);
 
-       if ((error = build_workdir_tree(&w_tree, index, b_commit)) < 0)
+       if ((error = build_workdir_tree(&w_tree, repo, i_index, b_commit)) < 0)
                goto cleanup;
 
        error = git_commit_create(
                w_commit_oid,
-               git_index_owner(index),
+               repo,
                NULL,
                stasher,
                stasher,
@@ -362,41 +431,39 @@ static int commit_worktree(
                parents);
 
 cleanup:
-       git_tree_free(i_tree);
        git_tree_free(w_tree);
+       git_index_free(i_index);
+       git_index_free(r_index);
        return error;
 }
 
-static int prepare_worktree_commit_message(
-       git_buf* msg,
-       const char *user_message)
+static int prepare_worktree_commit_message(git_buf *out, const char *user_message)
 {
        git_buf buf = GIT_BUF_INIT;
-       int error;
-
-       if ((error = git_buf_set(&buf, git_buf_cstr(msg), git_buf_len(msg))) < 0)
-               return error;
-
-       git_buf_clear(msg);
+       int error = 0;
 
-       if (!user_message)
-               git_buf_printf(msg, "WIP on %s", git_buf_cstr(&buf));
-       else {
+       if (!user_message) {
+               git_buf_printf(&buf, "WIP on %s", git_buf_cstr(out));
+       else {
                const char *colon;
 
-               if ((colon = strchr(git_buf_cstr(&buf), ':')) == NULL)
+               if ((colon = strchr(git_buf_cstr(out), ':')) == NULL)
                        goto cleanup;
 
-               git_buf_puts(msg, "On ");
-               git_buf_put(msg, git_buf_cstr(&buf), colon - buf.ptr);
-               git_buf_printf(msg, ": %s\n", user_message);
+               git_buf_puts(&buf, "On ");
+               git_buf_put(&buf, git_buf_cstr(out), colon - out->ptr);
+               git_buf_printf(&buf, ": %s\n", user_message);
        }
 
-       error = (git_buf_oom(msg) || git_buf_oom(&buf)) ? -1 : 0;
+       if (git_buf_oom(&buf)) {
+               error = -1;
+               goto cleanup;
+       }
 
-cleanup:
-       git_buf_free(&buf);
+       git_buf_swap(out, &buf);
 
+cleanup:
+       git_buf_dispose(&buf);
        return error;
 }
 
@@ -427,10 +494,7 @@ static int is_dirty_cb(const char *path, unsigned int status, void *payload)
        return GIT_PASSTHROUGH;
 }
 
-static int ensure_there_are_changes_to_stash(
-       git_repository *repo,
-       bool include_untracked_files,
-       bool include_ignored_files)
+static int ensure_there_are_changes_to_stash(git_repository *repo, uint32_t flags)
 {
        int error;
        git_status_options opts = GIT_STATUS_OPTIONS_INIT;
@@ -438,11 +502,11 @@ static int ensure_there_are_changes_to_stash(
        opts.show  = GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
        opts.flags = GIT_STATUS_OPT_EXCLUDE_SUBMODULES;
 
-       if (include_untracked_files)
+       if (flags & GIT_STASH_INCLUDE_UNTRACKED)
                opts.flags |= GIT_STATUS_OPT_INCLUDE_UNTRACKED |
                        GIT_STATUS_OPT_RECURSE_UNTRACKED_DIRS;
 
-       if (include_ignored_files)
+       if (flags & GIT_STASH_INCLUDE_IGNORED)
                opts.flags |= GIT_STATUS_OPT_INCLUDE_IGNORED |
                        GIT_STATUS_OPT_RECURSE_IGNORED_DIRS;
 
@@ -452,25 +516,19 @@ static int ensure_there_are_changes_to_stash(
                return 0;
 
        if (!error)
-               return create_error(GIT_ENOTFOUND, "There is nothing to stash.");
+               return create_error(GIT_ENOTFOUND, "there is nothing to stash.");
 
        return error;
 }
 
-static int reset_index_and_workdir(
-       git_repository *repo,
-       git_commit *commit,
-       bool remove_untracked,
-       bool remove_ignored)
+static int reset_index_and_workdir(git_repository *repo, git_commit *commit, uint32_t flags)
 {
        git_checkout_options opts = GIT_CHECKOUT_OPTIONS_INIT;
 
        opts.checkout_strategy = GIT_CHECKOUT_FORCE;
-
-       if (remove_untracked)
+       if (flags & GIT_STASH_INCLUDE_UNTRACKED)
                opts.checkout_strategy |= GIT_CHECKOUT_REMOVE_UNTRACKED;
-
-       if (remove_ignored)
+       if (flags & GIT_STASH_INCLUDE_IGNORED)
                opts.checkout_strategy |= GIT_CHECKOUT_REMOVE_IGNORED;
 
        return git_checkout_tree(repo, (git_object *)commit, &opts);
@@ -488,7 +546,9 @@ int git_stash_save(
        git_buf msg = GIT_BUF_INIT;
        int error;
 
-       assert(out && repo && stasher);
+       GIT_ASSERT_ARG(out);
+       GIT_ASSERT_ARG(repo);
+       GIT_ASSERT_ARG(stasher);
 
        if ((error = git_repository__ensure_not_bare(repo, "stash save")) < 0)
                return error;
@@ -496,31 +556,26 @@ int git_stash_save(
        if ((error = retrieve_base_commit_and_message(&b_commit, &msg, repo)) < 0)
                goto cleanup;
 
-       if ((error = ensure_there_are_changes_to_stash(
-               repo,
-               (flags & GIT_STASH_INCLUDE_UNTRACKED) != 0,
-               (flags & GIT_STASH_INCLUDE_IGNORED) != 0)) < 0)
+       if ((error = ensure_there_are_changes_to_stash(repo, flags)) < 0)
                goto cleanup;
 
        if ((error = git_repository_index(&index, repo)) < 0)
                goto cleanup;
 
-       if ((error = commit_index(
-                       &i_commit, index, stasher, git_buf_cstr(&msg), b_commit)) < 0)
+       if ((error = commit_index(&i_commit, repo, index, stasher,
+                                 git_buf_cstr(&msg), b_commit)) < 0)
                goto cleanup;
 
        if ((flags & (GIT_STASH_INCLUDE_UNTRACKED | GIT_STASH_INCLUDE_IGNORED)) &&
-               (error = commit_untracked(
-                       &u_commit, index, stasher, git_buf_cstr(&msg),
-                       i_commit, flags)) < 0)
+           (error = commit_untracked(&u_commit, repo, stasher,
+                                     git_buf_cstr(&msg), i_commit, flags)) < 0)
                goto cleanup;
 
        if ((error = prepare_worktree_commit_message(&msg, message)) < 0)
                goto cleanup;
 
-       if ((error = commit_worktree(
-                       out, index, stasher, git_buf_cstr(&msg),
-                       i_commit, b_commit, u_commit)) < 0)
+       if ((error = commit_worktree(out, repo, stasher, git_buf_cstr(&msg),
+                                    i_commit, b_commit, u_commit)) < 0)
                goto cleanup;
 
        git_buf_rtrim(&msg);
@@ -528,16 +583,13 @@ int git_stash_save(
        if ((error = update_reflog(out, repo, git_buf_cstr(&msg))) < 0)
                goto cleanup;
 
-       if ((error = reset_index_and_workdir(
-               repo,
-               ((flags & GIT_STASH_KEEP_INDEX) != 0) ? i_commit : b_commit,
-               (flags & GIT_STASH_INCLUDE_UNTRACKED) != 0,
-               (flags & GIT_STASH_INCLUDE_IGNORED) != 0)) < 0)
+       if ((error = reset_index_and_workdir(repo, (flags & GIT_STASH_KEEP_INDEX) ? i_commit : b_commit,
+                                            flags)) < 0)
                goto cleanup;
 
 cleanup:
 
-       git_buf_free(&msg);
+       git_buf_dispose(&msg);
        git_commit_free(i_commit);
        git_commit_free(b_commit);
        git_commit_free(u_commit);
@@ -564,9 +616,9 @@ static int retrieve_stash_commit(
                goto cleanup;
 
        max = git_reflog_entrycount(reflog);
-       if (index > max - 1) {
+       if (!max || index > max - 1) {
                error = GIT_ENOTFOUND;
-               giterr_set(GITERR_STASH, "No stashed state at position %" PRIuZ, index);
+               git_error_set(GIT_ERROR_STASH, "no stashed state at position %" PRIuZ, index);
                goto cleanup;
        }
 
@@ -645,187 +697,201 @@ cleanup:
        return error;
 }
 
-static int apply_index(
-       git_tree **unstashed_tree,
+static int merge_indexes(
+       git_index **out,
        git_repository *repo,
-       git_tree *start_index_tree,
-       git_tree *index_parent_tree,
-       git_tree *index_tree)
+       git_tree *ancestor_tree,
+       git_index *ours_index,
+       git_index *theirs_index)
 {
-       git_index *unstashed_index = NULL;
-       git_merge_options options = GIT_MERGE_OPTIONS_INIT;
+       git_iterator *ancestor = NULL, *ours = NULL, *theirs = NULL;
+       git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
        int error;
-       git_oid oid;
 
-       if ((error = git_merge_trees(
-                       &unstashed_index, repo, index_parent_tree,
-                       start_index_tree, index_tree, &options)) < 0)
-               goto cleanup;
+       iter_opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE;
 
-       if ((error = git_index_write_tree_to(&oid, unstashed_index, repo)) < 0)
-               goto cleanup;
+       if ((error = git_iterator_for_tree(&ancestor, ancestor_tree, &iter_opts)) < 0 ||
+               (error = git_iterator_for_index(&ours, repo, ours_index, &iter_opts)) < 0 ||
+               (error = git_iterator_for_index(&theirs, repo, theirs_index, &iter_opts)) < 0)
+               goto done;
 
-       if ((error = git_tree_lookup(unstashed_tree, repo, &oid)) < 0)
-               goto cleanup;
+       error = git_merge__iterators(out, repo, ancestor, ours, theirs, NULL);
 
-cleanup:
-       git_index_free(unstashed_index);
+done:
+       git_iterator_free(ancestor);
+       git_iterator_free(ours);
+       git_iterator_free(theirs);
        return error;
 }
 
-static int apply_untracked(
+static int merge_index_and_tree(
+       git_index **out,
        git_repository *repo,
-       git_tree *start_index_tree,
-       git_tree *untracked_tree)
+       git_tree *ancestor_tree,
+       git_index *ours_index,
+       git_tree *theirs_tree)
 {
-       git_checkout_options options = GIT_CHECKOUT_OPTIONS_INIT;
-       git_index *merged_index = NULL;
+       git_iterator *ancestor = NULL, *ours = NULL, *theirs = NULL;
+       git_iterator_options iter_opts = GIT_ITERATOR_OPTIONS_INIT;
        int error;
 
-       options.checkout_strategy =
-               GIT_CHECKOUT_SAFE | GIT_CHECKOUT_DONT_UPDATE_INDEX;
+       iter_opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE;
+
+       if ((error = git_iterator_for_tree(&ancestor, ancestor_tree, &iter_opts)) < 0 ||
+               (error = git_iterator_for_index(&ours, repo, ours_index, &iter_opts)) < 0 ||
+               (error = git_iterator_for_tree(&theirs, theirs_tree, &iter_opts)) < 0)
+               goto done;
 
-       if ((error = git_merge_trees(&merged_index,
-                       repo, NULL, start_index_tree, untracked_tree, NULL)) == 0)
-               error = git_checkout_index(repo, merged_index, &options);
+       error = git_merge__iterators(out, repo, ancestor, ours, theirs, NULL);
 
-       git_index_free(merged_index);
+done:
+       git_iterator_free(ancestor);
+       git_iterator_free(ours);
+       git_iterator_free(theirs);
        return error;
 }
 
-static int checkout_modified_notify_callback(
-       git_checkout_notify_t why,
-       const char *path,
-       const git_diff_file *baseline,
-       const git_diff_file *target,
-       const git_diff_file *workdir,
-       void *payload)
+static void normalize_apply_options(
+       git_stash_apply_options *opts,
+       const git_stash_apply_options *given_apply_opts)
 {
-       unsigned int status;
-       int error;
+       if (given_apply_opts != NULL) {
+               memcpy(opts, given_apply_opts, sizeof(git_stash_apply_options));
+       } else {
+               git_stash_apply_options default_apply_opts = GIT_STASH_APPLY_OPTIONS_INIT;
+               memcpy(opts, &default_apply_opts, sizeof(git_stash_apply_options));
+       }
 
-       GIT_UNUSED(why);
-       GIT_UNUSED(baseline);
-       GIT_UNUSED(target);
-       GIT_UNUSED(workdir);
+       opts->checkout_options.checkout_strategy |= GIT_CHECKOUT_NO_REFRESH;
 
-       if ((error = git_status_file(&status, payload, path)) < 0)
-               return error;
+       if (!opts->checkout_options.our_label)
+               opts->checkout_options.our_label = "Updated upstream";
 
-       if (status & GIT_STATUS_WT_MODIFIED) {
-               giterr_set(GITERR_STASH, "Local changes to '%s' would be overwritten", path);
-               return GIT_EMERGECONFLICT;
-       }
+       if (!opts->checkout_options.their_label)
+               opts->checkout_options.their_label = "Stashed changes";
+}
 
+int git_stash_apply_options_init(git_stash_apply_options *opts, unsigned int version)
+{
+       GIT_INIT_STRUCTURE_FROM_TEMPLATE(
+               opts, version, git_stash_apply_options, GIT_STASH_APPLY_OPTIONS_INIT);
        return 0;
 }
 
-static int apply_modified(
-       int *has_conflicts,
-       git_repository *repo,
-       git_tree *base_tree,
-       git_tree *start_index_tree,
-       git_tree *stash_tree,
-       unsigned int flags)
+#ifndef GIT_DEPRECATE_HARD
+int git_stash_apply_init_options(git_stash_apply_options *opts, unsigned int version)
 {
-       git_index *index = NULL;
-       git_merge_options merge_options = GIT_MERGE_OPTIONS_INIT;
-       git_checkout_options checkout_options = GIT_CHECKOUT_OPTIONS_INIT;
-       int error;
+       return git_stash_apply_options_init(opts, version);
+}
+#endif
+
+#define NOTIFY_PROGRESS(opts, progress_type)                           \
+       do {                                                            \
+               if ((opts).progress_cb &&                               \
+                   (error = (opts).progress_cb((progress_type), (opts).progress_payload))) { \
+                       error = (error < 0) ? error : -1;               \
+                       goto cleanup;                                   \
+               }                                                       \
+       } while(false);
+
+static int ensure_clean_index(git_repository *repo, git_index *index)
+{
+       git_tree *head_tree = NULL;
+       git_diff *index_diff = NULL;
+       int error = 0;
 
-       if ((error = git_merge_trees(
-                       &index, repo, base_tree,
-                       start_index_tree, stash_tree, &merge_options)) < 0)
-               goto cleanup;
+       if ((error = git_repository_head_tree(&head_tree, repo)) < 0 ||
+               (error = git_diff_tree_to_index(
+                       &index_diff, repo, head_tree, index, NULL)) < 0)
+               goto done;
 
-       checkout_options.checkout_strategy = GIT_CHECKOUT_SAFE | GIT_CHECKOUT_ALLOW_CONFLICTS;
-       if ((flags & GIT_APPLY_REINSTATE_INDEX) && !git_index_has_conflicts(index)) {
-               /* No need to update the index if it will be overridden later on */
-               checkout_options.checkout_strategy |= GIT_CHECKOUT_DONT_UPDATE_INDEX;
+       if (git_diff_num_deltas(index_diff) > 0) {
+               git_error_set(GIT_ERROR_STASH, "%" PRIuZ " uncommitted changes exist in the index",
+                       git_diff_num_deltas(index_diff));
+               error = GIT_EUNCOMMITTED;
        }
-       checkout_options.notify_flags = GIT_CHECKOUT_NOTIFY_CONFLICT;
-       checkout_options.notify_cb = checkout_modified_notify_callback;
-       checkout_options.notify_payload = repo;
-       checkout_options.our_label = "Updated upstream";
-       checkout_options.their_label = "Stashed changes";
-       if ((error = git_checkout_index(repo, index, &checkout_options)) < 0)
-               goto cleanup;
 
-       *has_conflicts = git_index_has_conflicts(index);
-
-cleanup:
-       git_index_free(index);
+done:
+       git_diff_free(index_diff);
+       git_tree_free(head_tree);
        return error;
 }
 
-static int unstage_modified_files(
-       git_repository *repo,
-       git_index *repo_index,
-       git_tree *unstashed_tree,
-       git_tree *start_index_tree)
+static int stage_new_file(const git_index_entry **entries, void *data)
 {
-       git_diff *diff = NULL;
-       git_diff_options options = GIT_DIFF_OPTIONS_INIT;
-       size_t i, count;
+       git_index *index = data;
+
+       if(entries[0] == NULL)
+               return git_index_add(index, entries[1]);
+       else
+               return git_index_add(index, entries[0]);
+}
+
+static int stage_new_files(
+       git_index **out,
+       git_tree *parent_tree,
+       git_tree *tree)
+{
+       git_iterator *iterators[2] = { NULL, NULL };
+       git_iterator_options iterator_options = GIT_ITERATOR_OPTIONS_INIT;
+       git_index *index = NULL;
        int error;
 
-       if (unstashed_tree) {
-               if ((error = git_index_read_tree(repo_index, unstashed_tree)) < 0)
-                       goto cleanup;
-       } else {
-               options.flags = GIT_DIFF_FORCE_BINARY;
-               if ((error = git_diff_tree_to_index(&diff, repo, start_index_tree,
-                               repo_index, &options)) < 0)
-                       goto cleanup;
+       if ((error = git_index_new(&index)) < 0 ||
+               (error = git_iterator_for_tree(
+                       &iterators[0], parent_tree, &iterator_options)) < 0 ||
+               (error = git_iterator_for_tree(
+                       &iterators[1], tree, &iterator_options)) < 0)
+               goto done;
 
-               /*
-                This behavior is not 100% similar to "git stash apply" as the latter uses
-                "git-read-tree --reset {treeish}" which preserves the stat()s from the
-                index instead of replacing them with the tree ones for identical files.
-                */
+       error = git_iterator_walk(iterators, 2, stage_new_file, index);
 
-               if ((error = git_index_read_tree(repo_index, start_index_tree)) < 0)
-                       goto cleanup;
+done:
+       if (error < 0)
+               git_index_free(index);
+       else
+               *out = index;
 
-               for (i = 0, count = git_diff_num_deltas(diff); i < count; ++i) {
-                       const git_diff_delta* delta = git_diff_get_delta(diff, i);
-                       if (delta->status == GIT_DELTA_ADDED) {
-                               if ((error = git_index_add_bypath(
-                                               repo_index, delta->new_file.path)) < 0)
-                                       goto cleanup;
-                       }
-               }
-       }
+       git_iterator_free(iterators[0]);
+       git_iterator_free(iterators[1]);
 
-cleanup:
-       git_diff_free(diff);
        return error;
 }
 
 int git_stash_apply(
        git_repository *repo,
        size_t index,
-       unsigned int flags)
+       const git_stash_apply_options *given_opts)
 {
+       git_stash_apply_options opts;
+       unsigned int checkout_strategy;
        git_commit *stash_commit = NULL;
        git_tree *stash_tree = NULL;
-       git_tree *base_tree = NULL;
+       git_tree *stash_parent_tree = NULL;
        git_tree *index_tree = NULL;
        git_tree *index_parent_tree = NULL;
        git_tree *untracked_tree = NULL;
+       git_index *stash_adds = NULL;
        git_index *repo_index = NULL;
-       git_tree *start_index_tree = NULL;
-       git_tree *unstashed_tree = NULL;
-       int has_conflicts;
+       git_index *unstashed_index = NULL;
+       git_index *modified_index = NULL;
+       git_index *untracked_index = NULL;
        int error;
 
+       GIT_ERROR_CHECK_VERSION(given_opts, GIT_STASH_APPLY_OPTIONS_VERSION, "git_stash_apply_options");
+
+       normalize_apply_options(&opts, given_opts);
+       checkout_strategy = opts.checkout_options.checkout_strategy;
+
+       NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_LOADING_STASH);
+
        /* Retrieve commit corresponding to the given stash */
        if ((error = retrieve_stash_commit(&stash_commit, repo, index)) < 0)
                goto cleanup;
 
        /* Retrieve all trees in the stash */
        if ((error = retrieve_stash_trees(
-                       &stash_tree, &base_tree, &index_tree,
+                       &stash_tree, &stash_parent_tree, &index_tree,
                        &index_parent_tree, &untracked_tree, stash_commit)) < 0)
                goto cleanup;
 
@@ -833,50 +899,100 @@ int git_stash_apply(
        if ((error = git_repository_index(&repo_index, repo)) < 0)
                goto cleanup;
 
-       /* Create tree from index */
-       if ((error = build_tree_from_index(&start_index_tree, repo_index)) < 0)
+       NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_ANALYZE_INDEX);
+
+       if ((error = ensure_clean_index(repo, repo_index)) < 0)
                goto cleanup;
 
        /* Restore index if required */
-       if ((flags & GIT_APPLY_REINSTATE_INDEX) &&
-               git_oid_cmp(git_tree_id(base_tree), git_tree_id(index_tree)) &&
-               git_oid_cmp(git_tree_id(start_index_tree), git_tree_id(index_tree))) {
+       if ((opts.flags & GIT_STASH_APPLY_REINSTATE_INDEX) &&
+               git_oid_cmp(git_tree_id(stash_parent_tree), git_tree_id(index_tree))) {
+
+               if ((error = merge_index_and_tree(
+                               &unstashed_index, repo, index_parent_tree, repo_index, index_tree)) < 0)
+                       goto cleanup;
 
-               if ((error = apply_index(
-                               &unstashed_tree, repo, start_index_tree,
-                               index_parent_tree, index_tree)) < 0)
+               if (git_index_has_conflicts(unstashed_index)) {
+                       error = GIT_ECONFLICT;
+                       goto cleanup;
+               }
+
+       /* Otherwise, stage any new files in the stash tree.  (Note: their
+        * previously unstaged contents are staged, not the previously staged.)
+        */
+       } else if ((opts.flags & GIT_STASH_APPLY_REINSTATE_INDEX) == 0) {
+               if ((error = stage_new_files(
+                               &stash_adds, stash_parent_tree, stash_tree)) < 0 ||
+                       (error = merge_indexes(
+                               &unstashed_index, repo, stash_parent_tree, repo_index, stash_adds)) < 0)
                        goto cleanup;
        }
 
+       NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_ANALYZE_MODIFIED);
+
+       /* Restore modified files in workdir */
+       if ((error = merge_index_and_tree(
+                       &modified_index, repo, stash_parent_tree, repo_index, stash_tree)) < 0)
+               goto cleanup;
+
        /* If applicable, restore untracked / ignored files in workdir */
        if (untracked_tree) {
-               if ((error = apply_untracked(repo, start_index_tree, untracked_tree)) < 0)
+               NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_ANALYZE_UNTRACKED);
+
+               if ((error = merge_index_and_tree(&untracked_index, repo, NULL, repo_index, untracked_tree)) < 0)
                        goto cleanup;
        }
 
-       /* Restore modified files in workdir */
-       if ((error = apply_modified(
-                       &has_conflicts, repo, base_tree, start_index_tree,
-                       stash_tree, flags)) < 0)
-               goto cleanup;
+       if (untracked_index) {
+               opts.checkout_options.checkout_strategy |= GIT_CHECKOUT_DONT_UPDATE_INDEX;
 
-       /* Unstage modified files from index unless there were merge conflicts */
-       if (!has_conflicts && (error = unstage_modified_files(
-                       repo, repo_index, unstashed_tree, start_index_tree)) < 0)
-               goto cleanup;
+               NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_CHECKOUT_UNTRACKED);
+
+               if ((error = git_checkout_index(repo, untracked_index, &opts.checkout_options)) < 0)
+                       goto cleanup;
+
+               opts.checkout_options.checkout_strategy = checkout_strategy;
+       }
+
+
+       /* If there are conflicts in the modified index, then we need to actually
+        * check that out as the repo's index.  Otherwise, we don't update the
+        * index.
+        */
+
+       if (!git_index_has_conflicts(modified_index))
+               opts.checkout_options.checkout_strategy |= GIT_CHECKOUT_DONT_UPDATE_INDEX;
 
-       /* Write updated index */
-       if ((error = git_index_write(repo_index)) < 0)
+       /* Check out the modified index using the existing repo index as baseline,
+        * so that existing modifications in the index can be rewritten even when
+        * checking out safely.
+        */
+       opts.checkout_options.baseline_index = repo_index;
+
+       NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_CHECKOUT_MODIFIED);
+
+       if ((error = git_checkout_index(repo, modified_index, &opts.checkout_options)) < 0)
                goto cleanup;
 
+       if (unstashed_index && !git_index_has_conflicts(modified_index)) {
+               if ((error = git_index_read_index(repo_index, unstashed_index)) < 0)
+                       goto cleanup;
+       }
+
+       NOTIFY_PROGRESS(opts, GIT_STASH_APPLY_PROGRESS_DONE);
+
+       error = git_index_write(repo_index);
+
 cleanup:
-       git_tree_free(unstashed_tree);
-       git_tree_free(start_index_tree);
+       git_index_free(untracked_index);
+       git_index_free(modified_index);
+       git_index_free(unstashed_index);
+       git_index_free(stash_adds);
        git_index_free(repo_index);
        git_tree_free(untracked_tree);
        git_tree_free(index_parent_tree);
        git_tree_free(index_tree);
-       git_tree_free(base_tree);
+       git_tree_free(stash_parent_tree);
        git_tree_free(stash_tree);
        git_commit_free(stash_commit);
        return error;
@@ -895,7 +1011,7 @@ int git_stash_foreach(
 
        error = git_reference_lookup(&stash, repo, GIT_REFS_STASH_FILE);
        if (error == GIT_ENOTFOUND) {
-               giterr_clear();
+               git_error_clear();
                return 0;
        }
        if (error < 0)
@@ -914,7 +1030,7 @@ int git_stash_foreach(
                        payload);
 
                if (error) {
-                       giterr_set_after_callback(error);
+                       git_error_set_after_callback(error);
                        break;
                }
        }
@@ -949,9 +1065,9 @@ int git_stash_drop(
 
        max = git_reflog_entrycount(reflog);
 
-       if (index > max - 1) {
+       if (!max || index > max - 1) {
                error = GIT_ENOTFOUND;
-               giterr_set(GITERR_STASH, "No stashed state at position %" PRIuZ, index);
+               git_error_set(GIT_ERROR_STASH, "no stashed state at position %" PRIuZ, index);
                goto cleanup;
        }
 
@@ -984,11 +1100,11 @@ cleanup:
 int git_stash_pop(
        git_repository *repo,
        size_t index,
-       unsigned int flags)
+       const git_stash_apply_options *options)
 {
        int error;
 
-       if ((error = git_stash_apply(repo, index, flags)) < 0)
+       if ((error = git_stash_apply(repo, index, options)) < 0)
                return error;
 
        return git_stash_drop(repo, index);