restore: default to --source=HEAD when only --staged is specified
[gitweb.git] / builtin / checkout.c
index f7967cdb7c9eca20e40ba5edc2224c79f10f766f..09a03f1ff874683d02fc3deb1608a29e310149b1 100644 (file)
@@ -24,6 +24,7 @@
 #include "tree.h"
 #include "tree-walk.h"
 #include "unpack-trees.h"
+#include "wt-status.h"
 #include "xdiff-interface.h"
 
 static const char * const checkout_usage[] = {
@@ -37,6 +38,11 @@ static const char * const switch_branch_usage[] = {
        NULL,
 };
 
+static const char * const restore_usage[] = {
+       N_("git restore [<options>] [--source=<branch>] <file>..."),
+       NULL,
+};
+
 struct checkout_opts {
        int patch_mode;
        int quiet;
@@ -53,9 +59,15 @@ struct checkout_opts {
        int overlay_mode;
        int dwim_new_local_branch;
        int discard_changes;
+       int accept_ref;
        int accept_pathspec;
        int switch_branch_doing_nothing_is_ok;
        int only_merge_on_switching_branches;
+       int can_switch_when_in_progress;
+       int orphan_from_empty_tree;
+       int empty_pathspec_ok;
+       int checkout_index;
+       int checkout_worktree;
 
        const char *new_branch;
        const char *new_branch_force;
@@ -68,6 +80,7 @@ struct checkout_opts {
        int branch_exists;
        const char *prefix;
        struct pathspec pathspec;
+       const char *from_treeish;
        struct tree *source_tree;
 };
 
@@ -319,17 +332,74 @@ static void mark_ce_for_checkout_no_overlay(struct cache_entry *ce,
        }
 }
 
+static int checkout_worktree(const struct checkout_opts *opts)
+{
+       struct checkout state = CHECKOUT_INIT;
+       int nr_checkouts = 0, nr_unmerged = 0;
+       int errs = 0;
+       int pos;
+
+       state.force = 1;
+       state.refresh_cache = 1;
+       state.istate = &the_index;
+
+       enable_delayed_checkout(&state);
+       for (pos = 0; pos < active_nr; pos++) {
+               struct cache_entry *ce = active_cache[pos];
+               if (ce->ce_flags & CE_MATCHED) {
+                       if (!ce_stage(ce)) {
+                               errs |= checkout_entry(ce, &state,
+                                                      NULL, &nr_checkouts);
+                               continue;
+                       }
+                       if (opts->writeout_stage)
+                               errs |= checkout_stage(opts->writeout_stage,
+                                                      ce, pos,
+                                                      &state,
+                                                      &nr_checkouts, opts->overlay_mode);
+                       else if (opts->merge)
+                               errs |= checkout_merged(pos, &state,
+                                                       &nr_unmerged);
+                       pos = skip_same_name(ce, pos) - 1;
+               }
+       }
+       remove_marked_cache_entries(&the_index, 1);
+       remove_scheduled_dirs();
+       errs |= finish_delayed_checkout(&state, &nr_checkouts);
+
+       if (opts->count_checkout_paths) {
+               if (nr_unmerged)
+                       fprintf_ln(stderr, Q_("Recreated %d merge conflict",
+                                             "Recreated %d merge conflicts",
+                                             nr_unmerged),
+                                  nr_unmerged);
+               if (opts->source_tree)
+                       fprintf_ln(stderr, Q_("Updated %d path from %s",
+                                             "Updated %d paths from %s",
+                                             nr_checkouts),
+                                  nr_checkouts,
+                                  find_unique_abbrev(&opts->source_tree->object.oid,
+                                                     DEFAULT_ABBREV));
+               else if (!nr_unmerged || nr_checkouts)
+                       fprintf_ln(stderr, Q_("Updated %d path from the index",
+                                             "Updated %d paths from the index",
+                                             nr_checkouts),
+                                  nr_checkouts);
+       }
+
+       return errs;
+}
+
 static int checkout_paths(const struct checkout_opts *opts,
                          const char *revision)
 {
        int pos;
-       struct checkout state = CHECKOUT_INIT;
        static char *ps_matched;
        struct object_id rev;
        struct commit *head;
        int errs = 0;
        struct lock_file lock_file = LOCK_INIT;
-       int nr_checkouts = 0, nr_unmerged = 0;
+       int checkout_index;
 
        trace2_cmd_mode(opts->patch_mode ? "patch" : "path");
 
@@ -355,9 +425,36 @@ static int checkout_paths(const struct checkout_opts *opts,
                die(_("Cannot update paths and switch to branch '%s' at the same time."),
                    opts->new_branch);
 
-       if (opts->patch_mode)
-               return run_add_interactive(revision, "--patch=checkout",
-                                          &opts->pathspec);
+       if (!opts->checkout_worktree && !opts->checkout_index)
+               die(_("neither '%s' or '%s' is specified"),
+                   "--staged", "--worktree");
+
+       if (!opts->checkout_worktree && !opts->from_treeish)
+               die(_("'%s' must be used when '%s' is not specified"),
+                   "--worktree", "--source");
+
+       if (opts->checkout_index && !opts->checkout_worktree &&
+           opts->writeout_stage)
+               die(_("'%s' or '%s' cannot be used with %s"),
+                   "--ours", "--theirs", "--staged");
+
+       if (opts->checkout_index && !opts->checkout_worktree &&
+           opts->merge)
+               die(_("'%s' or '%s' cannot be used with %s"),
+                   "--merge", "--conflict", "--staged");
+
+       if (opts->patch_mode) {
+               const char *patch_mode;
+
+               if (opts->checkout_index && opts->checkout_worktree)
+                       patch_mode = "--patch=checkout";
+               else if (opts->checkout_index && !opts->checkout_worktree)
+                       patch_mode = "--patch=reset";
+               else
+                       die(_("'%s' with only '%s' is not currently supported"),
+                           "--patch", "--worktree");
+               return run_add_interactive(revision, patch_mode, &opts->pathspec);
+       }
 
        repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
        if (read_cache_preload(&opts->pathspec) < 0)
@@ -415,57 +512,31 @@ static int checkout_paths(const struct checkout_opts *opts,
                return 1;
 
        /* Now we are committed to check them out */
-       state.force = 1;
-       state.refresh_cache = 1;
-       state.istate = &the_index;
+       if (opts->checkout_worktree)
+               errs |= checkout_worktree(opts);
 
-       enable_delayed_checkout(&state);
-       for (pos = 0; pos < active_nr; pos++) {
-               struct cache_entry *ce = active_cache[pos];
-               if (ce->ce_flags & CE_MATCHED) {
-                       if (!ce_stage(ce)) {
-                               errs |= checkout_entry(ce, &state,
-                                                      NULL, &nr_checkouts);
-                               continue;
-                       }
-                       if (opts->writeout_stage)
-                               errs |= checkout_stage(opts->writeout_stage,
-                                                      ce, pos,
-                                                      &state,
-                                                      &nr_checkouts, opts->overlay_mode);
-                       else if (opts->merge)
-                               errs |= checkout_merged(pos, &state,
-                                                       &nr_unmerged);
-                       pos = skip_same_name(ce, pos) - 1;
-               }
-       }
-       remove_marked_cache_entries(&the_index, 1);
-       remove_scheduled_dirs();
-       errs |= finish_delayed_checkout(&state, &nr_checkouts);
+       /*
+        * Allow updating the index when checking out from the index.
+        * This is to save new stat info.
+        */
+       if (opts->checkout_worktree && !opts->checkout_index && !opts->source_tree)
+               checkout_index = 1;
+       else
+               checkout_index = opts->checkout_index;
 
-       if (opts->count_checkout_paths) {
-               if (nr_unmerged)
-                       fprintf_ln(stderr, Q_("Recreated %d merge conflict",
-                                             "Recreated %d merge conflicts",
-                                             nr_unmerged),
-                                  nr_unmerged);
-               if (opts->source_tree)
-                       fprintf_ln(stderr, Q_("Updated %d path from %s",
-                                             "Updated %d paths from %s",
-                                             nr_checkouts),
-                                  nr_checkouts,
-                                  find_unique_abbrev(&opts->source_tree->object.oid,
-                                                     DEFAULT_ABBREV));
-               else if (!nr_unmerged || nr_checkouts)
-                       fprintf_ln(stderr, Q_("Updated %d path from the index",
-                                             "Updated %d paths from the index",
-                                             nr_checkouts),
-                                  nr_checkouts);
+       if (checkout_index) {
+               if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
+                       die(_("unable to write new index file"));
+       } else {
+               /*
+                * NEEDSWORK: if --worktree is not specified, we
+                * should save stat info of checked out files in the
+                * index to avoid the next (potentially costly)
+                * refresh. But it's a bit tricker to do...
+                */
+               rollback_lock_file(&lock_file);
        }
 
-       if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
-               die(_("unable to write new index file"));
-
        read_ref_full("HEAD", 0, &rev, NULL);
        head = lookup_commit_reference_gently(the_repository, &rev, 1);
 
@@ -566,15 +637,21 @@ static int merge_working_tree(const struct checkout_opts *opts,
 {
        int ret;
        struct lock_file lock_file = LOCK_INIT;
+       struct tree *new_tree;
 
        hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
        if (read_cache_preload(NULL) < 0)
                return error(_("index file corrupt"));
 
        resolve_undo_clear();
+       if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
+               if (new_branch_info->commit)
+                       BUG("'switch --orphan' should never accept a commit as starting point");
+               new_tree = parse_tree_indirect(the_hash_algo->empty_tree);
+       } else
+               new_tree = get_commit_tree(new_branch_info->commit);
        if (opts->discard_changes) {
-               ret = reset_tree(get_commit_tree(new_branch_info->commit),
-                                opts, 1, writeout_error);
+               ret = reset_tree(new_tree, opts, 1, writeout_error);
                if (ret)
                        return ret;
        } else {
@@ -612,7 +689,8 @@ static int merge_working_tree(const struct checkout_opts *opts,
                                           &old_branch_info->commit->object.oid :
                                           the_hash_algo->empty_tree);
                init_tree_desc(&trees[0], tree->buffer, tree->size);
-               tree = parse_tree_indirect(&new_branch_info->commit->object.oid);
+               parse_tree(new_tree);
+               tree = new_tree;
                init_tree_desc(&trees[1], tree->buffer, tree->size);
 
                ret = unpack_trees(2, trees, &topts);
@@ -661,7 +739,7 @@ static int merge_working_tree(const struct checkout_opts *opts,
                        o.verbosity = 0;
                        work = write_tree_from_memory(&o);
 
-                       ret = reset_tree(get_commit_tree(new_branch_info->commit),
+                       ret = reset_tree(new_tree,
                                         opts, 1,
                                         writeout_error);
                        if (ret)
@@ -670,13 +748,13 @@ static int merge_working_tree(const struct checkout_opts *opts,
                        o.branch1 = new_branch_info->name;
                        o.branch2 = "local";
                        ret = merge_trees(&o,
-                                         get_commit_tree(new_branch_info->commit),
+                                         new_tree,
                                          work,
                                          get_commit_tree(old_branch_info->commit),
                                          &result);
                        if (ret < 0)
                                exit(128);
-                       ret = reset_tree(get_commit_tree(new_branch_info->commit),
+                       ret = reset_tree(new_tree,
                                         opts, 0,
                                         writeout_error);
                        strbuf_release(&o.obuf);
@@ -694,7 +772,7 @@ static int merge_working_tree(const struct checkout_opts *opts,
        if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
                die(_("unable to write new index file"));
 
-       if (!opts->discard_changes && !opts->quiet)
+       if (!opts->discard_changes && !opts->quiet && new_branch_info->commit)
                show_local_changes(&new_branch_info->commit->object, &opts->diff_options);
 
        return 0;
@@ -895,7 +973,10 @@ static void orphaned_commit_warning(struct commit *old_commit, struct commit *ne
        add_pending_object(&revs, object, oid_to_hex(&object->oid));
 
        for_each_ref(add_pending_uninteresting_ref, &revs);
-       add_pending_oid(&revs, "HEAD", &new_commit->object.oid, UNINTERESTING);
+       if (new_commit)
+               add_pending_oid(&revs, "HEAD",
+                               &new_commit->object.oid,
+                               UNINTERESTING);
 
        if (prepare_revision_walk(&revs))
                die(_("internal error in revision walk"));
@@ -930,6 +1011,14 @@ static int switch_branches(const struct checkout_opts *opts,
        if (old_branch_info.path)
                skip_prefix(old_branch_info.path, "refs/heads/", &old_branch_info.name);
 
+       if (opts->new_orphan_branch && opts->orphan_from_empty_tree) {
+               if (new_branch_info->name)
+                       BUG("'switch --orphan' should never accept a commit as starting point");
+               new_branch_info->commit = NULL;
+               new_branch_info->name = "(empty)";
+               do_merge = 1;
+       }
+
        if (!new_branch_info->name) {
                new_branch_info->name = "HEAD";
                new_branch_info->commit = old_branch_info.commit;
@@ -1202,6 +1291,39 @@ static void die_expecting_a_branch(const struct branch_info *branch_info)
        die(_("a branch is expected, got '%s'"), branch_info->name);
 }
 
+static void die_if_some_operation_in_progress(void)
+{
+       struct wt_status_state state;
+
+       memset(&state, 0, sizeof(state));
+       wt_status_get_state(the_repository, &state, 0);
+
+       if (state.merge_in_progress)
+               die(_("cannot switch branch while merging\n"
+                     "Consider \"git merge --quit\" "
+                     "or \"git worktree add\"."));
+       if (state.am_in_progress)
+               die(_("cannot switch branch in the middle of an am session\n"
+                     "Consider \"git am --quit\" "
+                     "or \"git worktree add\"."));
+       if (state.rebase_interactive_in_progress || state.rebase_in_progress)
+               die(_("cannot switch branch while rebasing\n"
+                     "Consider \"git rebase --quit\" "
+                     "or \"git worktree add\"."));
+       if (state.cherry_pick_in_progress)
+               die(_("cannot switch branch while cherry-picking\n"
+                     "Consider \"git cherry-pick --quit\" "
+                     "or \"git worktree add\"."));
+       if (state.revert_in_progress)
+               die(_("cannot switch branch while reverting\n"
+                     "Consider \"git revert --quit\" "
+                     "or \"git worktree add\"."));
+       if (state.bisect_in_progress)
+               die(_("cannot switch branch while bisecting\n"
+                     "Consider \"git bisect reset HEAD\" "
+                     "or \"git worktree add\"."));
+}
+
 static int checkout_branch(struct checkout_opts *opts,
                           struct branch_info *new_branch_info)
 {
@@ -1212,9 +1334,9 @@ static int checkout_branch(struct checkout_opts *opts,
                die(_("'%s' cannot be used with switching branches"),
                    "--patch");
 
-       if (!opts->overlay_mode)
+       if (opts->overlay_mode != -1)
                die(_("'%s' cannot be used with switching branches"),
-                   "--no-overlay");
+                   "--[no]-overlay");
 
        if (opts->writeout_stage)
                die(_("'%s' cannot be used with switching branches"),
@@ -1233,6 +1355,8 @@ static int checkout_branch(struct checkout_opts *opts,
        if (opts->new_orphan_branch) {
                if (opts->track != BRANCH_TRACK_UNSPECIFIED)
                        die(_("'%s' cannot be used with '%s'"), "--orphan", "-t");
+               if (opts->orphan_from_empty_tree && new_branch_info->name)
+                       die(_("'%s' cannot take <start-point>"), "--orphan");
        } else if (opts->force_detach) {
                if (opts->track != BRANCH_TRACK_UNSPECIFIED)
                        die(_("'%s' cannot be used with '%s'"), "--detach", "-t");
@@ -1257,6 +1381,9 @@ static int checkout_branch(struct checkout_opts *opts,
            !new_branch_info->path)
                die_expecting_a_branch(new_branch_info);
 
+       if (!opts->can_switch_when_in_progress)
+               die_if_some_operation_in_progress();
+
        if (new_branch_info->path && !opts->force_detach && !opts->new_branch &&
            !opts->ignore_other_worktrees) {
                int flag;
@@ -1332,7 +1459,6 @@ static struct option *add_checkout_path_options(struct checkout_opts *opts,
                OPT_BOOL('p', "patch", &opts->patch_mode, N_("select hunks interactively")),
                OPT_BOOL(0, "ignore-skip-worktree-bits", &opts->ignore_skipworktree,
                         N_("do not limit pathspecs to sparse entries only")),
-               OPT_BOOL(0, "overlay", &opts->overlay_mode, N_("use overlay mode (default)")),
                OPT_END()
        };
        struct option *newopts = parse_options_concat(prevopts, options);
@@ -1346,19 +1472,24 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
 {
        struct branch_info new_branch_info;
        int dwim_remotes_matched = 0;
+       int parseopt_flags = 0;
 
        memset(&new_branch_info, 0, sizeof(new_branch_info));
        opts->overwrite_ignore = 1;
        opts->prefix = prefix;
        opts->show_progress = -1;
-       opts->overlay_mode = -1;
 
        git_config(git_checkout_config, opts);
 
        opts->track = BRANCH_TRACK_UNSPECIFIED;
 
-       argc = parse_options(argc, argv, prefix, options, usagestr,
-                            PARSE_OPT_KEEP_DASHDASH);
+       if (!opts->accept_pathspec && !opts->accept_ref)
+               BUG("make up your mind, you need to take _something_");
+       if (opts->accept_pathspec && opts->accept_ref)
+               parseopt_flags = PARSE_OPT_KEEP_DASHDASH;
+
+       argc = parse_options(argc, argv, prefix, options,
+                            usagestr, parseopt_flags);
 
        if (opts->show_progress < 0) {
                if (opts->quiet)
@@ -1380,6 +1511,26 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
        if (opts->overlay_mode == 1 && opts->patch_mode)
                die(_("-p and --overlay are mutually exclusive"));
 
+       if (opts->checkout_index >= 0 || opts->checkout_worktree >= 0) {
+               if (opts->checkout_index < 0)
+                       opts->checkout_index = 0;
+               if (opts->checkout_worktree < 0)
+                       opts->checkout_worktree = 0;
+       } else {
+               if (opts->checkout_index < 0)
+                       opts->checkout_index = -opts->checkout_index - 1;
+               if (opts->checkout_worktree < 0)
+                       opts->checkout_worktree = -opts->checkout_worktree - 1;
+       }
+       if (opts->checkout_index < 0 || opts->checkout_worktree < 0)
+               BUG("these flags should be non-negative by now");
+       /*
+        * convenient shortcut: "git restore --staged" equals
+        * "git restore --staged --source HEAD"
+        */
+       if (!opts->from_treeish && opts->checkout_index && !opts->checkout_worktree)
+               opts->from_treeish = "HEAD";
+
        /*
         * From here on, new_branch will contain the branch to be checked out,
         * and new_branch_force and new_orphan_branch will tell us which one of
@@ -1417,7 +1568,7 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
         * including "last branch" syntax and DWIM-ery for names of
         * remote branches, erroring out for invalid or ambiguous cases.
         */
-       if (argc) {
+       if (argc && opts->accept_ref) {
                struct object_id rev;
                int dwim_ok =
                        !opts->patch_mode &&
@@ -1429,8 +1580,24 @@ static int checkout_main(int argc, const char **argv, const char *prefix,
                                             &dwim_remotes_matched);
                argv += n;
                argc -= n;
+       } else if (!opts->accept_ref && opts->from_treeish) {
+               struct object_id rev;
+
+               if (get_oid_mb(opts->from_treeish, &rev))
+                       die(_("could not resolve %s"), opts->from_treeish);
+
+               setup_new_branch_info_and_source_tree(&new_branch_info,
+                                                     opts, &rev,
+                                                     opts->from_treeish);
+
+               if (!opts->source_tree)
+                       die(_("reference is not a tree: %s"), opts->from_treeish);
        }
 
+       if (opts->accept_pathspec && !opts->empty_pathspec_ok && !argc &&
+           !opts->patch_mode)  /* patch mode is special */
+               die(_("you must specify path(s) to restore"));
+
        if (argc) {
                parse_pathspec(&opts->pathspec, 0,
                               opts->patch_mode ? PATHSPEC_PREFIX_ORIGIN : 0,
@@ -1504,6 +1671,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
                OPT_BOOL('l', NULL, &opts.new_branch_log, N_("create reflog for new branch")),
                OPT_BOOL(0, "guess", &opts.dwim_new_local_branch,
                         N_("second guess 'git checkout <no-such-branch>' (default)")),
+               OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode (default)")),
                OPT_END()
        };
        int ret;
@@ -1512,8 +1680,15 @@ int cmd_checkout(int argc, const char **argv, const char *prefix)
        opts.dwim_new_local_branch = 1;
        opts.switch_branch_doing_nothing_is_ok = 1;
        opts.only_merge_on_switching_branches = 0;
+       opts.accept_ref = 1;
        opts.accept_pathspec = 1;
        opts.implicit_detach = 1;
+       opts.can_switch_when_in_progress = 1;
+       opts.orphan_from_empty_tree = 0;
+       opts.empty_pathspec_ok = 1;
+       opts.overlay_mode = -1;
+       opts.checkout_index = -2;    /* default on */
+       opts.checkout_worktree = -2; /* default on */
 
        options = parse_options_dup(checkout_options);
        options = add_common_options(&opts, options);
@@ -1545,10 +1720,14 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
 
        memset(&opts, 0, sizeof(opts));
        opts.dwim_new_local_branch = 1;
+       opts.accept_ref = 1;
        opts.accept_pathspec = 0;
        opts.switch_branch_doing_nothing_is_ok = 0;
        opts.only_merge_on_switching_branches = 1;
        opts.implicit_detach = 0;
+       opts.can_switch_when_in_progress = 0;
+       opts.orphan_from_empty_tree = 1;
+       opts.overlay_mode = -1;
 
        options = parse_options_dup(switch_options);
        options = add_common_options(&opts, options);
@@ -1559,3 +1738,37 @@ int cmd_switch(int argc, const char **argv, const char *prefix)
        FREE_AND_NULL(options);
        return ret;
 }
+
+int cmd_restore(int argc, const char **argv, const char *prefix)
+{
+       struct checkout_opts opts;
+       struct option *options;
+       struct option restore_options[] = {
+               OPT_STRING('s', "source", &opts.from_treeish, "<tree-ish>",
+                          N_("where the checkout from")),
+               OPT_BOOL('S', "staged", &opts.checkout_index,
+                          N_("restore the index")),
+               OPT_BOOL('W', "worktree", &opts.checkout_worktree,
+                          N_("restore the working tree (default)")),
+               OPT_BOOL(0, "overlay", &opts.overlay_mode, N_("use overlay mode")),
+               OPT_END()
+       };
+       int ret;
+
+       memset(&opts, 0, sizeof(opts));
+       opts.accept_ref = 0;
+       opts.accept_pathspec = 1;
+       opts.empty_pathspec_ok = 0;
+       opts.overlay_mode = 0;
+       opts.checkout_index = -1;    /* default off */
+       opts.checkout_worktree = -2; /* default on */
+
+       options = parse_options_dup(restore_options);
+       options = add_common_options(&opts, options);
+       options = add_checkout_path_options(&opts, options);
+
+       ret = checkout_main(argc, argv, prefix, &opts,
+                           options, restore_usage);
+       FREE_AND_NULL(options);
+       return ret;
+}