builtin-reset.con commit reset: add test cases for "--keep" option (ffbc5dc)
   1/*
   2 * "git reset" builtin command
   3 *
   4 * Copyright (c) 2007 Carlos Rica
   5 *
   6 * Based on git-reset.sh, which is
   7 *
   8 * Copyright (c) 2005, 2006 Linus Torvalds and Junio C Hamano
   9 */
  10#include "cache.h"
  11#include "tag.h"
  12#include "object.h"
  13#include "commit.h"
  14#include "run-command.h"
  15#include "refs.h"
  16#include "diff.h"
  17#include "diffcore.h"
  18#include "tree.h"
  19#include "branch.h"
  20#include "parse-options.h"
  21#include "unpack-trees.h"
  22#include "cache-tree.h"
  23
  24static const char * const git_reset_usage[] = {
  25        "git reset [--mixed | --soft | --hard | --merge | --keep] [-q] [<commit>]",
  26        "git reset [--mixed] <commit> [--] <paths>...",
  27        NULL
  28};
  29
  30enum reset_type { MIXED, SOFT, HARD, MERGE, KEEP, NONE };
  31static const char *reset_type_names[] = {
  32        "mixed", "soft", "hard", "merge", "keep", NULL
  33};
  34
  35static char *args_to_str(const char **argv)
  36{
  37        char *buf = NULL;
  38        unsigned long len, space = 0, nr = 0;
  39
  40        for (; *argv; argv++) {
  41                len = strlen(*argv);
  42                ALLOC_GROW(buf, nr + 1 + len, space);
  43                if (nr)
  44                        buf[nr++] = ' ';
  45                memcpy(buf + nr, *argv, len);
  46                nr += len;
  47        }
  48        ALLOC_GROW(buf, nr + 1, space);
  49        buf[nr] = '\0';
  50
  51        return buf;
  52}
  53
  54static inline int is_merge(void)
  55{
  56        return !access(git_path("MERGE_HEAD"), F_OK);
  57}
  58
  59static int reset_index_file(const unsigned char *sha1, int reset_type, int quiet)
  60{
  61        int nr = 1;
  62        int newfd;
  63        struct tree_desc desc[2];
  64        struct unpack_trees_options opts;
  65        struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
  66
  67        memset(&opts, 0, sizeof(opts));
  68        opts.head_idx = 1;
  69        opts.src_index = &the_index;
  70        opts.dst_index = &the_index;
  71        opts.fn = oneway_merge;
  72        opts.merge = 1;
  73        if (!quiet)
  74                opts.verbose_update = 1;
  75        switch (reset_type) {
  76        case KEEP:
  77        case MERGE:
  78                opts.update = 1;
  79                break;
  80        case HARD:
  81                opts.update = 1;
  82                /* fallthrough */
  83        default:
  84                opts.reset = 1;
  85        }
  86
  87        newfd = hold_locked_index(lock, 1);
  88
  89        read_cache_unmerged();
  90
  91        if (reset_type == KEEP) {
  92                unsigned char head_sha1[20];
  93                if (get_sha1("HEAD", head_sha1))
  94                        return error("You do not have a valid HEAD.");
  95                if (!fill_tree_descriptor(desc, head_sha1))
  96                        return error("Failed to find tree of HEAD.");
  97                nr++;
  98                opts.fn = twoway_merge;
  99        }
 100
 101        if (!fill_tree_descriptor(desc + nr - 1, sha1))
 102                return error("Failed to find tree of %s.", sha1_to_hex(sha1));
 103        if (unpack_trees(nr, desc, &opts))
 104                return -1;
 105        if (write_cache(newfd, active_cache, active_nr) ||
 106            commit_locked_index(lock))
 107                return error("Could not write new index file.");
 108
 109        return 0;
 110}
 111
 112static void print_new_head_line(struct commit *commit)
 113{
 114        const char *hex, *body;
 115
 116        hex = find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV);
 117        printf("HEAD is now at %s", hex);
 118        body = strstr(commit->buffer, "\n\n");
 119        if (body) {
 120                const char *eol;
 121                size_t len;
 122                body += 2;
 123                eol = strchr(body, '\n');
 124                len = eol ? eol - body : strlen(body);
 125                printf(" %.*s\n", (int) len, body);
 126        }
 127        else
 128                printf("\n");
 129}
 130
 131static int update_index_refresh(int fd, struct lock_file *index_lock, int flags)
 132{
 133        int result;
 134
 135        if (!index_lock) {
 136                index_lock = xcalloc(1, sizeof(struct lock_file));
 137                fd = hold_locked_index(index_lock, 1);
 138        }
 139
 140        if (read_cache() < 0)
 141                return error("Could not read index");
 142
 143        result = refresh_index(&the_index, (flags), NULL, NULL,
 144                               "Unstaged changes after reset:") ? 1 : 0;
 145        if (write_cache(fd, active_cache, active_nr) ||
 146                        commit_locked_index(index_lock))
 147                return error ("Could not refresh index");
 148        return result;
 149}
 150
 151static void update_index_from_diff(struct diff_queue_struct *q,
 152                struct diff_options *opt, void *data)
 153{
 154        int i;
 155        int *discard_flag = data;
 156
 157        /* do_diff_cache() mangled the index */
 158        discard_cache();
 159        *discard_flag = 1;
 160        read_cache();
 161
 162        for (i = 0; i < q->nr; i++) {
 163                struct diff_filespec *one = q->queue[i]->one;
 164                if (one->mode) {
 165                        struct cache_entry *ce;
 166                        ce = make_cache_entry(one->mode, one->sha1, one->path,
 167                                0, 0);
 168                        if (!ce)
 169                                die("make_cache_entry failed for path '%s'",
 170                                    one->path);
 171                        add_cache_entry(ce, ADD_CACHE_OK_TO_ADD |
 172                                ADD_CACHE_OK_TO_REPLACE);
 173                } else
 174                        remove_file_from_cache(one->path);
 175        }
 176}
 177
 178static int interactive_reset(const char *revision, const char **argv,
 179                             const char *prefix)
 180{
 181        const char **pathspec = NULL;
 182
 183        if (*argv)
 184                pathspec = get_pathspec(prefix, argv);
 185
 186        return run_add_interactive(revision, "--patch=reset", pathspec);
 187}
 188
 189static int read_from_tree(const char *prefix, const char **argv,
 190                unsigned char *tree_sha1, int refresh_flags)
 191{
 192        struct lock_file *lock = xcalloc(1, sizeof(struct lock_file));
 193        int index_fd, index_was_discarded = 0;
 194        struct diff_options opt;
 195
 196        memset(&opt, 0, sizeof(opt));
 197        diff_tree_setup_paths(get_pathspec(prefix, (const char **)argv), &opt);
 198        opt.output_format = DIFF_FORMAT_CALLBACK;
 199        opt.format_callback = update_index_from_diff;
 200        opt.format_callback_data = &index_was_discarded;
 201
 202        index_fd = hold_locked_index(lock, 1);
 203        index_was_discarded = 0;
 204        read_cache();
 205        if (do_diff_cache(tree_sha1, &opt))
 206                return 1;
 207        diffcore_std(&opt);
 208        diff_flush(&opt);
 209        diff_tree_release_paths(&opt);
 210
 211        if (!index_was_discarded)
 212                /* The index is still clobbered from do_diff_cache() */
 213                discard_cache();
 214        return update_index_refresh(index_fd, lock, refresh_flags);
 215}
 216
 217static void prepend_reflog_action(const char *action, char *buf, size_t size)
 218{
 219        const char *sep = ": ";
 220        const char *rla = getenv("GIT_REFLOG_ACTION");
 221        if (!rla)
 222                rla = sep = "";
 223        if (snprintf(buf, size, "%s%s%s", rla, sep, action) >= size)
 224                warning("Reflog action message too long: %.*s...", 50, buf);
 225}
 226
 227int cmd_reset(int argc, const char **argv, const char *prefix)
 228{
 229        int i = 0, reset_type = NONE, update_ref_status = 0, quiet = 0;
 230        int patch_mode = 0;
 231        const char *rev = "HEAD";
 232        unsigned char sha1[20], *orig = NULL, sha1_orig[20],
 233                                *old_orig = NULL, sha1_old_orig[20];
 234        struct commit *commit;
 235        char *reflog_action, msg[1024];
 236        const struct option options[] = {
 237                OPT__QUIET(&quiet),
 238                OPT_SET_INT(0, "mixed", &reset_type,
 239                                                "reset HEAD and index", MIXED),
 240                OPT_SET_INT(0, "soft", &reset_type, "reset only HEAD", SOFT),
 241                OPT_SET_INT(0, "hard", &reset_type,
 242                                "reset HEAD, index and working tree", HARD),
 243                OPT_SET_INT(0, "merge", &reset_type,
 244                                "reset HEAD, index and working tree", MERGE),
 245                OPT_SET_INT(0, "keep", &reset_type,
 246                                "reset HEAD but keep local changes", KEEP),
 247                OPT_BOOLEAN('p', "patch", &patch_mode, "select hunks interactively"),
 248                OPT_END()
 249        };
 250
 251        git_config(git_default_config, NULL);
 252
 253        argc = parse_options(argc, argv, prefix, options, git_reset_usage,
 254                                                PARSE_OPT_KEEP_DASHDASH);
 255        reflog_action = args_to_str(argv);
 256        setenv("GIT_REFLOG_ACTION", reflog_action, 0);
 257
 258        /*
 259         * Possible arguments are:
 260         *
 261         * git reset [-opts] <rev> <paths>...
 262         * git reset [-opts] <rev> -- <paths>...
 263         * git reset [-opts] -- <paths>...
 264         * git reset [-opts] <paths>...
 265         *
 266         * At this point, argv[i] points immediately after [-opts].
 267         */
 268
 269        if (i < argc) {
 270                if (!strcmp(argv[i], "--")) {
 271                        i++; /* reset to HEAD, possibly with paths */
 272                } else if (i + 1 < argc && !strcmp(argv[i+1], "--")) {
 273                        rev = argv[i];
 274                        i += 2;
 275                }
 276                /*
 277                 * Otherwise, argv[i] could be either <rev> or <paths> and
 278                 * has to be unambiguous.
 279                 */
 280                else if (!get_sha1(argv[i], sha1)) {
 281                        /*
 282                         * Ok, argv[i] looks like a rev; it should not
 283                         * be a filename.
 284                         */
 285                        verify_non_filename(prefix, argv[i]);
 286                        rev = argv[i++];
 287                } else {
 288                        /* Otherwise we treat this as a filename */
 289                        verify_filename(prefix, argv[i]);
 290                }
 291        }
 292
 293        if (get_sha1(rev, sha1))
 294                die("Failed to resolve '%s' as a valid ref.", rev);
 295
 296        commit = lookup_commit_reference(sha1);
 297        if (!commit)
 298                die("Could not parse object '%s'.", rev);
 299        hashcpy(sha1, commit->object.sha1);
 300
 301        if (patch_mode) {
 302                if (reset_type != NONE)
 303                        die("--patch is incompatible with --{hard,mixed,soft}");
 304                return interactive_reset(rev, argv + i, prefix);
 305        }
 306
 307        /* git reset tree [--] paths... can be used to
 308         * load chosen paths from the tree into the index without
 309         * affecting the working tree nor HEAD. */
 310        if (i < argc) {
 311                if (reset_type == MIXED)
 312                        warning("--mixed option is deprecated with paths.");
 313                else if (reset_type != NONE)
 314                        die("Cannot do %s reset with paths.",
 315                                        reset_type_names[reset_type]);
 316                return read_from_tree(prefix, argv + i, sha1,
 317                                quiet ? REFRESH_QUIET : REFRESH_IN_PORCELAIN);
 318        }
 319        if (reset_type == NONE)
 320                reset_type = MIXED; /* by default */
 321
 322        if (reset_type == HARD || reset_type == MERGE)
 323                setup_work_tree();
 324
 325        if (reset_type == MIXED && is_bare_repository())
 326                die("%s reset is not allowed in a bare repository",
 327                    reset_type_names[reset_type]);
 328
 329        /* Soft reset does not touch the index file nor the working tree
 330         * at all, but requires them in a good order.  Other resets reset
 331         * the index file to the tree object we are switching to. */
 332        if (reset_type == SOFT) {
 333                if (is_merge() || read_cache() < 0 || unmerged_cache())
 334                        die("Cannot do a soft reset in the middle of a merge.");
 335        } else {
 336                int err = reset_index_file(sha1, reset_type, quiet);
 337                if (reset_type == KEEP)
 338                        err = err || reset_index_file(sha1, MIXED, quiet);
 339                if (err)
 340                        die("Could not reset index file to revision '%s'.", rev);
 341        }
 342
 343        /* Any resets update HEAD to the head being switched to,
 344         * saving the previous head in ORIG_HEAD before. */
 345        if (!get_sha1("ORIG_HEAD", sha1_old_orig))
 346                old_orig = sha1_old_orig;
 347        if (!get_sha1("HEAD", sha1_orig)) {
 348                orig = sha1_orig;
 349                prepend_reflog_action("updating ORIG_HEAD", msg, sizeof(msg));
 350                update_ref(msg, "ORIG_HEAD", orig, old_orig, 0, MSG_ON_ERR);
 351        }
 352        else if (old_orig)
 353                delete_ref("ORIG_HEAD", old_orig, 0);
 354        prepend_reflog_action("updating HEAD", msg, sizeof(msg));
 355        update_ref_status = update_ref(msg, "HEAD", sha1, orig, 0, MSG_ON_ERR);
 356
 357        switch (reset_type) {
 358        case HARD:
 359                if (!update_ref_status && !quiet)
 360                        print_new_head_line(commit);
 361                break;
 362        case SOFT: /* Nothing else to do. */
 363                break;
 364        case MIXED: /* Report what has not been updated. */
 365                update_index_refresh(0, NULL,
 366                                quiet ? REFRESH_QUIET : REFRESH_IN_PORCELAIN);
 367                break;
 368        }
 369
 370        remove_branch_state();
 371
 372        free(reflog_action);
 373
 374        return update_ref_status;
 375}