4c51b58206070bd7e15373b30074f405d7529aae
   1#include "builtin.h"
   2#include "config.h"
   3#include "parse-options.h"
   4#include "refs.h"
   5#include "lockfile.h"
   6#include "cache-tree.h"
   7#include "unpack-trees.h"
   8#include "merge-recursive.h"
   9#include "argv-array.h"
  10#include "run-command.h"
  11#include "dir.h"
  12#include "rerere.h"
  13#include "revision.h"
  14#include "log-tree.h"
  15#include "diffcore.h"
  16
  17#define INCLUDE_ALL_FILES 2
  18
  19static const char * const git_stash_helper_usage[] = {
  20        N_("git stash--helper list [<options>]"),
  21        N_("git stash--helper show [<options>] [<stash>]"),
  22        N_("git stash--helper drop [-q|--quiet] [<stash>]"),
  23        N_("git stash--helper ( pop | apply ) [--index] [-q|--quiet] [<stash>]"),
  24        N_("git stash--helper branch <branchname> [<stash>]"),
  25        N_("git stash--helper clear"),
  26        N_("git stash--helper [push [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
  27           "          [-u|--include-untracked] [-a|--all] [-m|--message <message>]\n"
  28           "          [--] [<pathspec>...]]"),
  29        N_("git stash--helper save [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
  30           "          [-u|--include-untracked] [-a|--all] [<message>]"),
  31        NULL
  32};
  33
  34static const char * const git_stash_helper_list_usage[] = {
  35        N_("git stash--helper list [<options>]"),
  36        NULL
  37};
  38
  39static const char * const git_stash_helper_show_usage[] = {
  40        N_("git stash--helper show [<options>] [<stash>]"),
  41        NULL
  42};
  43
  44static const char * const git_stash_helper_drop_usage[] = {
  45        N_("git stash--helper drop [-q|--quiet] [<stash>]"),
  46        NULL
  47};
  48
  49static const char * const git_stash_helper_pop_usage[] = {
  50        N_("git stash--helper pop [--index] [-q|--quiet] [<stash>]"),
  51        NULL
  52};
  53
  54static const char * const git_stash_helper_apply_usage[] = {
  55        N_("git stash--helper apply [--index] [-q|--quiet] [<stash>]"),
  56        NULL
  57};
  58
  59static const char * const git_stash_helper_branch_usage[] = {
  60        N_("git stash--helper branch <branchname> [<stash>]"),
  61        NULL
  62};
  63
  64static const char * const git_stash_helper_clear_usage[] = {
  65        N_("git stash--helper clear"),
  66        NULL
  67};
  68
  69static const char * const git_stash_helper_store_usage[] = {
  70        N_("git stash--helper store [-m|--message <message>] [-q|--quiet] <commit>"),
  71        NULL
  72};
  73
  74static const char * const git_stash_helper_create_usage[] = {
  75        N_("git stash--helper create [<message>]"),
  76        NULL
  77};
  78
  79static const char * const git_stash_helper_push_usage[] = {
  80        N_("git stash--helper [push [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
  81           "          [-u|--include-untracked] [-a|--all] [-m|--message <message>]\n"
  82           "          [--] [<pathspec>...]]"),
  83        NULL
  84};
  85
  86static const char * const git_stash_helper_save_usage[] = {
  87        N_("git stash--helper save [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
  88           "          [-u|--include-untracked] [-a|--all] [<message>]"),
  89        NULL
  90};
  91
  92static const char *ref_stash = "refs/stash";
  93static struct strbuf stash_index_path = STRBUF_INIT;
  94
  95/*
  96 * w_commit is set to the commit containing the working tree
  97 * b_commit is set to the base commit
  98 * i_commit is set to the commit containing the index tree
  99 * u_commit is set to the commit containing the untracked files tree
 100 * w_tree is set to the working tree
 101 * b_tree is set to the base tree
 102 * i_tree is set to the index tree
 103 * u_tree is set to the untracked files tree
 104 */
 105struct stash_info {
 106        struct object_id w_commit;
 107        struct object_id b_commit;
 108        struct object_id i_commit;
 109        struct object_id u_commit;
 110        struct object_id w_tree;
 111        struct object_id b_tree;
 112        struct object_id i_tree;
 113        struct object_id u_tree;
 114        struct strbuf revision;
 115        int is_stash_ref;
 116        int has_u;
 117};
 118
 119static void free_stash_info(struct stash_info *info)
 120{
 121        strbuf_release(&info->revision);
 122}
 123
 124static void assert_stash_like(struct stash_info *info, const char *revision)
 125{
 126        if (get_oidf(&info->b_commit, "%s^1", revision) ||
 127            get_oidf(&info->w_tree, "%s:", revision) ||
 128            get_oidf(&info->b_tree, "%s^1:", revision) ||
 129            get_oidf(&info->i_tree, "%s^2:", revision))
 130                die(_("'%s' is not a stash-like commit"), revision);
 131}
 132
 133static int get_stash_info(struct stash_info *info, int argc, const char **argv)
 134{
 135        int ret;
 136        char *end_of_rev;
 137        char *expanded_ref;
 138        const char *revision;
 139        const char *commit = NULL;
 140        struct object_id dummy;
 141        struct strbuf symbolic = STRBUF_INIT;
 142
 143        if (argc > 1) {
 144                int i;
 145                struct strbuf refs_msg = STRBUF_INIT;
 146
 147                for (i = 0; i < argc; i++)
 148                        strbuf_addf(&refs_msg, " '%s'", argv[i]);
 149
 150                fprintf_ln(stderr, _("Too many revisions specified:%s"),
 151                           refs_msg.buf);
 152                strbuf_release(&refs_msg);
 153
 154                return -1;
 155        }
 156
 157        if (argc == 1)
 158                commit = argv[0];
 159
 160        strbuf_init(&info->revision, 0);
 161        if (!commit) {
 162                if (!ref_exists(ref_stash)) {
 163                        free_stash_info(info);
 164                        fprintf_ln(stderr, _("No stash entries found."));
 165                        return -1;
 166                }
 167
 168                strbuf_addf(&info->revision, "%s@{0}", ref_stash);
 169        } else if (strspn(commit, "0123456789") == strlen(commit)) {
 170                strbuf_addf(&info->revision, "%s@{%s}", ref_stash, commit);
 171        } else {
 172                strbuf_addstr(&info->revision, commit);
 173        }
 174
 175        revision = info->revision.buf;
 176
 177        if (get_oid(revision, &info->w_commit)) {
 178                error(_("%s is not a valid reference"), revision);
 179                free_stash_info(info);
 180                return -1;
 181        }
 182
 183        assert_stash_like(info, revision);
 184
 185        info->has_u = !get_oidf(&info->u_tree, "%s^3:", revision);
 186
 187        end_of_rev = strchrnul(revision, '@');
 188        strbuf_add(&symbolic, revision, end_of_rev - revision);
 189
 190        ret = dwim_ref(symbolic.buf, symbolic.len, &dummy, &expanded_ref);
 191        strbuf_release(&symbolic);
 192        switch (ret) {
 193        case 0: /* Not found, but valid ref */
 194                info->is_stash_ref = 0;
 195                break;
 196        case 1:
 197                info->is_stash_ref = !strcmp(expanded_ref, ref_stash);
 198                break;
 199        default: /* Invalid or ambiguous */
 200                free_stash_info(info);
 201        }
 202
 203        free(expanded_ref);
 204        return !(ret == 0 || ret == 1);
 205}
 206
 207static int do_clear_stash(void)
 208{
 209        struct object_id obj;
 210        if (get_oid(ref_stash, &obj))
 211                return 0;
 212
 213        return delete_ref(NULL, ref_stash, &obj, 0);
 214}
 215
 216static int clear_stash(int argc, const char **argv, const char *prefix)
 217{
 218        struct option options[] = {
 219                OPT_END()
 220        };
 221
 222        argc = parse_options(argc, argv, prefix, options,
 223                             git_stash_helper_clear_usage,
 224                             PARSE_OPT_STOP_AT_NON_OPTION);
 225
 226        if (argc)
 227                return error(_("git stash clear with parameters is "
 228                               "unimplemented"));
 229
 230        return do_clear_stash();
 231}
 232
 233static int reset_tree(struct object_id *i_tree, int update, int reset)
 234{
 235        int nr_trees = 1;
 236        struct unpack_trees_options opts;
 237        struct tree_desc t[MAX_UNPACK_TREES];
 238        struct tree *tree;
 239        struct lock_file lock_file = LOCK_INIT;
 240
 241        read_cache_preload(NULL);
 242        if (refresh_cache(REFRESH_QUIET))
 243                return -1;
 244
 245        hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
 246
 247        memset(&opts, 0, sizeof(opts));
 248
 249        tree = parse_tree_indirect(i_tree);
 250        if (parse_tree(tree))
 251                return -1;
 252
 253        init_tree_desc(t, tree->buffer, tree->size);
 254
 255        opts.head_idx = 1;
 256        opts.src_index = &the_index;
 257        opts.dst_index = &the_index;
 258        opts.merge = 1;
 259        opts.reset = reset;
 260        opts.update = update;
 261        opts.fn = oneway_merge;
 262
 263        if (unpack_trees(nr_trees, t, &opts))
 264                return -1;
 265
 266        if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
 267                return error(_("unable to write new index file"));
 268
 269        return 0;
 270}
 271
 272static int diff_tree_binary(struct strbuf *out, struct object_id *w_commit)
 273{
 274        struct child_process cp = CHILD_PROCESS_INIT;
 275        const char *w_commit_hex = oid_to_hex(w_commit);
 276
 277        /*
 278         * Diff-tree would not be very hard to replace with a native function,
 279         * however it should be done together with apply_cached.
 280         */
 281        cp.git_cmd = 1;
 282        argv_array_pushl(&cp.args, "diff-tree", "--binary", NULL);
 283        argv_array_pushf(&cp.args, "%s^2^..%s^2", w_commit_hex, w_commit_hex);
 284
 285        return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
 286}
 287
 288static int apply_cached(struct strbuf *out)
 289{
 290        struct child_process cp = CHILD_PROCESS_INIT;
 291
 292        /*
 293         * Apply currently only reads either from stdin or a file, thus
 294         * apply_all_patches would have to be updated to optionally take a
 295         * buffer.
 296         */
 297        cp.git_cmd = 1;
 298        argv_array_pushl(&cp.args, "apply", "--cached", NULL);
 299        return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
 300}
 301
 302static int reset_head(void)
 303{
 304        struct child_process cp = CHILD_PROCESS_INIT;
 305
 306        /*
 307         * Reset is overall quite simple, however there is no current public
 308         * API for resetting.
 309         */
 310        cp.git_cmd = 1;
 311        argv_array_push(&cp.args, "reset");
 312
 313        return run_command(&cp);
 314}
 315
 316static void add_diff_to_buf(struct diff_queue_struct *q,
 317                            struct diff_options *options,
 318                            void *data)
 319{
 320        int i;
 321
 322        for (i = 0; i < q->nr; i++) {
 323                strbuf_addstr(data, q->queue[i]->one->path);
 324
 325                /* NUL-terminate: will be fed to update-index -z */
 326                strbuf_addch(data, '\0');
 327        }
 328}
 329
 330static int get_newly_staged(struct strbuf *out, struct object_id *c_tree)
 331{
 332        struct child_process cp = CHILD_PROCESS_INIT;
 333        const char *c_tree_hex = oid_to_hex(c_tree);
 334
 335        /*
 336         * diff-index is very similar to diff-tree above, and should be
 337         * converted together with update_index.
 338         */
 339        cp.git_cmd = 1;
 340        argv_array_pushl(&cp.args, "diff-index", "--cached", "--name-only",
 341                         "--diff-filter=A", NULL);
 342        argv_array_push(&cp.args, c_tree_hex);
 343        return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
 344}
 345
 346static int update_index(struct strbuf *out)
 347{
 348        struct child_process cp = CHILD_PROCESS_INIT;
 349
 350        /*
 351         * Update-index is very complicated and may need to have a public
 352         * function exposed in order to remove this forking.
 353         */
 354        cp.git_cmd = 1;
 355        argv_array_pushl(&cp.args, "update-index", "--add", "--stdin", NULL);
 356        return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
 357}
 358
 359static int restore_untracked(struct object_id *u_tree)
 360{
 361        int res;
 362        struct child_process cp = CHILD_PROCESS_INIT;
 363
 364        /*
 365         * We need to run restore files from a given index, but without
 366         * affecting the current index, so we use GIT_INDEX_FILE with
 367         * run_command to fork processes that will not interfere.
 368         */
 369        cp.git_cmd = 1;
 370        argv_array_push(&cp.args, "read-tree");
 371        argv_array_push(&cp.args, oid_to_hex(u_tree));
 372        argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s",
 373                         stash_index_path.buf);
 374        if (run_command(&cp)) {
 375                remove_path(stash_index_path.buf);
 376                return -1;
 377        }
 378
 379        child_process_init(&cp);
 380        cp.git_cmd = 1;
 381        argv_array_pushl(&cp.args, "checkout-index", "--all", NULL);
 382        argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s",
 383                         stash_index_path.buf);
 384
 385        res = run_command(&cp);
 386        remove_path(stash_index_path.buf);
 387        return res;
 388}
 389
 390static int do_apply_stash(const char *prefix, struct stash_info *info,
 391                          int index, int quiet)
 392{
 393        int ret;
 394        int has_index = index;
 395        struct merge_options o;
 396        struct object_id c_tree;
 397        struct object_id index_tree;
 398        struct commit *result;
 399        const struct object_id *bases[1];
 400
 401        read_cache_preload(NULL);
 402        if (refresh_cache(REFRESH_QUIET))
 403                return -1;
 404
 405        if (write_cache_as_tree(&c_tree, 0, NULL))
 406                return error(_("cannot apply a stash in the middle of a merge"));
 407
 408        if (index) {
 409                if (oideq(&info->b_tree, &info->i_tree) ||
 410                    oideq(&c_tree, &info->i_tree)) {
 411                        has_index = 0;
 412                } else {
 413                        struct strbuf out = STRBUF_INIT;
 414
 415                        if (diff_tree_binary(&out, &info->w_commit)) {
 416                                strbuf_release(&out);
 417                                return error(_("could not generate diff %s^!."),
 418                                             oid_to_hex(&info->w_commit));
 419                        }
 420
 421                        ret = apply_cached(&out);
 422                        strbuf_release(&out);
 423                        if (ret)
 424                                return error(_("conflicts in index."
 425                                               "Try without --index."));
 426
 427                        discard_cache();
 428                        read_cache();
 429                        if (write_cache_as_tree(&index_tree, 0, NULL))
 430                                return error(_("could not save index tree"));
 431
 432                        reset_head();
 433                }
 434        }
 435
 436        if (info->has_u && restore_untracked(&info->u_tree))
 437                return error(_("could not restore untracked files from stash"));
 438
 439        init_merge_options(&o);
 440
 441        o.branch1 = "Updated upstream";
 442        o.branch2 = "Stashed changes";
 443
 444        if (oideq(&info->b_tree, &c_tree))
 445                o.branch1 = "Version stash was based on";
 446
 447        if (quiet)
 448                o.verbosity = 0;
 449
 450        if (o.verbosity >= 3)
 451                printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
 452
 453        bases[0] = &info->b_tree;
 454
 455        ret = merge_recursive_generic(&o, &c_tree, &info->w_tree, 1, bases,
 456                                      &result);
 457        if (ret) {
 458                rerere(0);
 459
 460                if (index)
 461                        fprintf_ln(stderr, _("Index was not unstashed."));
 462
 463                return ret;
 464        }
 465
 466        if (has_index) {
 467                if (reset_tree(&index_tree, 0, 0))
 468                        return -1;
 469        } else {
 470                struct strbuf out = STRBUF_INIT;
 471
 472                if (get_newly_staged(&out, &c_tree)) {
 473                        strbuf_release(&out);
 474                        return -1;
 475                }
 476
 477                if (reset_tree(&c_tree, 0, 1)) {
 478                        strbuf_release(&out);
 479                        return -1;
 480                }
 481
 482                ret = update_index(&out);
 483                strbuf_release(&out);
 484                if (ret)
 485                        return -1;
 486
 487                discard_cache();
 488        }
 489
 490        if (quiet) {
 491                if (refresh_cache(REFRESH_QUIET))
 492                        warning("could not refresh index");
 493        } else {
 494                struct child_process cp = CHILD_PROCESS_INIT;
 495
 496                /*
 497                 * Status is quite simple and could be replaced with calls to
 498                 * wt_status in the future, but it adds complexities which may
 499                 * require more tests.
 500                 */
 501                cp.git_cmd = 1;
 502                cp.dir = prefix;
 503                argv_array_push(&cp.args, "status");
 504                run_command(&cp);
 505        }
 506
 507        return 0;
 508}
 509
 510static int apply_stash(int argc, const char **argv, const char *prefix)
 511{
 512        int ret;
 513        int quiet = 0;
 514        int index = 0;
 515        struct stash_info info;
 516        struct option options[] = {
 517                OPT__QUIET(&quiet, N_("be quiet, only report errors")),
 518                OPT_BOOL(0, "index", &index,
 519                         N_("attempt to recreate the index")),
 520                OPT_END()
 521        };
 522
 523        argc = parse_options(argc, argv, prefix, options,
 524                             git_stash_helper_apply_usage, 0);
 525
 526        if (get_stash_info(&info, argc, argv))
 527                return -1;
 528
 529        ret = do_apply_stash(prefix, &info, index, quiet);
 530        free_stash_info(&info);
 531        return ret;
 532}
 533
 534static int do_drop_stash(const char *prefix, struct stash_info *info, int quiet)
 535{
 536        int ret;
 537        struct child_process cp_reflog = CHILD_PROCESS_INIT;
 538        struct child_process cp = CHILD_PROCESS_INIT;
 539
 540        /*
 541         * reflog does not provide a simple function for deleting refs. One will
 542         * need to be added to avoid implementing too much reflog code here
 543         */
 544
 545        cp_reflog.git_cmd = 1;
 546        argv_array_pushl(&cp_reflog.args, "reflog", "delete", "--updateref",
 547                         "--rewrite", NULL);
 548        argv_array_push(&cp_reflog.args, info->revision.buf);
 549        ret = run_command(&cp_reflog);
 550        if (!ret) {
 551                if (!quiet)
 552                        printf_ln(_("Dropped %s (%s)"), info->revision.buf,
 553                                  oid_to_hex(&info->w_commit));
 554        } else {
 555                return error(_("%s: Could not drop stash entry"),
 556                             info->revision.buf);
 557        }
 558
 559        /*
 560         * This could easily be replaced by get_oid, but currently it will throw
 561         * a fatal error when a reflog is empty, which we can not recover from.
 562         */
 563        cp.git_cmd = 1;
 564        /* Even though --quiet is specified, rev-parse still outputs the hash */
 565        cp.no_stdout = 1;
 566        argv_array_pushl(&cp.args, "rev-parse", "--verify", "--quiet", NULL);
 567        argv_array_pushf(&cp.args, "%s@{0}", ref_stash);
 568        ret = run_command(&cp);
 569
 570        /* do_clear_stash if we just dropped the last stash entry */
 571        if (ret)
 572                do_clear_stash();
 573
 574        return 0;
 575}
 576
 577static void assert_stash_ref(struct stash_info *info)
 578{
 579        if (!info->is_stash_ref) {
 580                error(_("'%s' is not a stash reference"), info->revision.buf);
 581                free_stash_info(info);
 582                exit(1);
 583        }
 584}
 585
 586static int drop_stash(int argc, const char **argv, const char *prefix)
 587{
 588        int ret;
 589        int quiet = 0;
 590        struct stash_info info;
 591        struct option options[] = {
 592                OPT__QUIET(&quiet, N_("be quiet, only report errors")),
 593                OPT_END()
 594        };
 595
 596        argc = parse_options(argc, argv, prefix, options,
 597                             git_stash_helper_drop_usage, 0);
 598
 599        if (get_stash_info(&info, argc, argv))
 600                return -1;
 601
 602        assert_stash_ref(&info);
 603
 604        ret = do_drop_stash(prefix, &info, quiet);
 605        free_stash_info(&info);
 606        return ret;
 607}
 608
 609static int pop_stash(int argc, const char **argv, const char *prefix)
 610{
 611        int ret;
 612        int index = 0;
 613        int quiet = 0;
 614        struct stash_info info;
 615        struct option options[] = {
 616                OPT__QUIET(&quiet, N_("be quiet, only report errors")),
 617                OPT_BOOL(0, "index", &index,
 618                         N_("attempt to recreate the index")),
 619                OPT_END()
 620        };
 621
 622        argc = parse_options(argc, argv, prefix, options,
 623                             git_stash_helper_pop_usage, 0);
 624
 625        if (get_stash_info(&info, argc, argv))
 626                return -1;
 627
 628        assert_stash_ref(&info);
 629        if ((ret = do_apply_stash(prefix, &info, index, quiet)))
 630                printf_ln(_("The stash entry is kept in case "
 631                            "you need it again."));
 632        else
 633                ret = do_drop_stash(prefix, &info, quiet);
 634
 635        free_stash_info(&info);
 636        return ret;
 637}
 638
 639static int branch_stash(int argc, const char **argv, const char *prefix)
 640{
 641        int ret;
 642        const char *branch = NULL;
 643        struct stash_info info;
 644        struct child_process cp = CHILD_PROCESS_INIT;
 645        struct option options[] = {
 646                OPT_END()
 647        };
 648
 649        argc = parse_options(argc, argv, prefix, options,
 650                             git_stash_helper_branch_usage, 0);
 651
 652        if (!argc) {
 653                fprintf_ln(stderr, _("No branch name specified"));
 654                return -1;
 655        }
 656
 657        branch = argv[0];
 658
 659        if (get_stash_info(&info, argc - 1, argv + 1))
 660                return -1;
 661
 662        cp.git_cmd = 1;
 663        argv_array_pushl(&cp.args, "checkout", "-b", NULL);
 664        argv_array_push(&cp.args, branch);
 665        argv_array_push(&cp.args, oid_to_hex(&info.b_commit));
 666        ret = run_command(&cp);
 667        if (!ret)
 668                ret = do_apply_stash(prefix, &info, 1, 0);
 669        if (!ret && info.is_stash_ref)
 670                ret = do_drop_stash(prefix, &info, 0);
 671
 672        free_stash_info(&info);
 673
 674        return ret;
 675}
 676
 677static int list_stash(int argc, const char **argv, const char *prefix)
 678{
 679        struct child_process cp = CHILD_PROCESS_INIT;
 680        struct option options[] = {
 681                OPT_END()
 682        };
 683
 684        argc = parse_options(argc, argv, prefix, options,
 685                             git_stash_helper_list_usage,
 686                             PARSE_OPT_KEEP_UNKNOWN);
 687
 688        if (!ref_exists(ref_stash))
 689                return 0;
 690
 691        cp.git_cmd = 1;
 692        argv_array_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
 693                         "--first-parent", "-m", NULL);
 694        argv_array_pushv(&cp.args, argv);
 695        argv_array_push(&cp.args, ref_stash);
 696        argv_array_push(&cp.args, "--");
 697        return run_command(&cp);
 698}
 699
 700static int show_stat = 1;
 701static int show_patch;
 702
 703static int git_stash_config(const char *var, const char *value, void *cb)
 704{
 705        if (!strcmp(var, "stash.showstat")) {
 706                show_stat = git_config_bool(var, value);
 707                return 0;
 708        }
 709        if (!strcmp(var, "stash.showpatch")) {
 710                show_patch = git_config_bool(var, value);
 711                return 0;
 712        }
 713        return git_default_config(var, value, cb);
 714}
 715
 716static int show_stash(int argc, const char **argv, const char *prefix)
 717{
 718        int i;
 719        int opts = 0;
 720        int ret = 0;
 721        struct stash_info info;
 722        struct rev_info rev;
 723        struct argv_array stash_args = ARGV_ARRAY_INIT;
 724        struct option options[] = {
 725                OPT_END()
 726        };
 727
 728        init_diff_ui_defaults();
 729        git_config(git_diff_ui_config, NULL);
 730        init_revisions(&rev, prefix);
 731
 732        for (i = 1; i < argc; i++) {
 733                if (argv[i][0] != '-')
 734                        argv_array_push(&stash_args, argv[i]);
 735                else
 736                        opts++;
 737        }
 738
 739        ret = get_stash_info(&info, stash_args.argc, stash_args.argv);
 740        argv_array_clear(&stash_args);
 741        if (ret)
 742                return -1;
 743
 744        /*
 745         * The config settings are applied only if there are not passed
 746         * any options.
 747         */
 748        if (!opts) {
 749                git_config(git_stash_config, NULL);
 750                if (show_stat)
 751                        rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
 752
 753                if (show_patch)
 754                        rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
 755
 756                if (!show_stat && !show_patch) {
 757                        free_stash_info(&info);
 758                        return 0;
 759                }
 760        }
 761
 762        argc = setup_revisions(argc, argv, &rev, NULL);
 763        if (argc > 1) {
 764                free_stash_info(&info);
 765                usage_with_options(git_stash_helper_show_usage, options);
 766        }
 767
 768        rev.diffopt.flags.recursive = 1;
 769        setup_diff_pager(&rev.diffopt);
 770        diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
 771        log_tree_diff_flush(&rev);
 772
 773        free_stash_info(&info);
 774        return diff_result_code(&rev.diffopt, 0);
 775}
 776
 777static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
 778                          int quiet)
 779{
 780        if (!stash_msg)
 781                stash_msg = "Created via \"git stash store\".";
 782
 783        if (update_ref(stash_msg, ref_stash, w_commit, NULL,
 784                       REF_FORCE_CREATE_REFLOG,
 785                       quiet ? UPDATE_REFS_QUIET_ON_ERR :
 786                       UPDATE_REFS_MSG_ON_ERR)) {
 787                if (!quiet) {
 788                        fprintf_ln(stderr, _("Cannot update %s with %s"),
 789                                   ref_stash, oid_to_hex(w_commit));
 790                }
 791                return -1;
 792        }
 793
 794        return 0;
 795}
 796
 797static int store_stash(int argc, const char **argv, const char *prefix)
 798{
 799        int quiet = 0;
 800        const char *stash_msg = NULL;
 801        struct object_id obj;
 802        struct object_context dummy;
 803        struct option options[] = {
 804                OPT__QUIET(&quiet, N_("be quiet")),
 805                OPT_STRING('m', "message", &stash_msg, "message",
 806                           N_("stash message")),
 807                OPT_END()
 808        };
 809
 810        argc = parse_options(argc, argv, prefix, options,
 811                             git_stash_helper_store_usage,
 812                             PARSE_OPT_KEEP_UNKNOWN);
 813
 814        if (argc != 1) {
 815                if (!quiet)
 816                        fprintf_ln(stderr, _("\"git stash store\" requires one "
 817                                             "<commit> argument"));
 818                return -1;
 819        }
 820
 821        if (get_oid_with_context(argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
 822                                 &dummy)) {
 823                if (!quiet)
 824                        fprintf_ln(stderr, _("Cannot update %s with %s"),
 825                                             ref_stash, argv[0]);
 826                return -1;
 827        }
 828
 829        return do_store_stash(&obj, stash_msg, quiet);
 830}
 831
 832static void add_pathspecs(struct argv_array *args,
 833                          struct pathspec ps) {
 834        int i;
 835
 836        for (i = 0; i < ps.nr; i++)
 837                argv_array_push(args, ps.items[i].match);
 838}
 839
 840/*
 841 * `untracked_files` will be filled with the names of untracked files.
 842 * The return value is:
 843 *
 844 * = 0 if there are not any untracked files
 845 * > 0 if there are untracked files
 846 */
 847static int get_untracked_files(struct pathspec ps, int include_untracked,
 848                               struct strbuf *untracked_files)
 849{
 850        int i;
 851        int max_len;
 852        int found = 0;
 853        char *seen;
 854        struct dir_struct dir;
 855
 856        memset(&dir, 0, sizeof(dir));
 857        if (include_untracked != INCLUDE_ALL_FILES)
 858                setup_standard_excludes(&dir);
 859
 860        seen = xcalloc(ps.nr, 1);
 861
 862        max_len = fill_directory(&dir, the_repository->index, &ps);
 863        for (i = 0; i < dir.nr; i++) {
 864                struct dir_entry *ent = dir.entries[i];
 865                if (dir_path_match(&the_index, ent, &ps, max_len, seen)) {
 866                        found++;
 867                        strbuf_addstr(untracked_files, ent->name);
 868                        /* NUL-terminate: will be fed to update-index -z */
 869                        strbuf_addch(untracked_files, '\0');
 870                }
 871                free(ent);
 872        }
 873
 874        free(seen);
 875        free(dir.entries);
 876        free(dir.ignored);
 877        clear_directory(&dir);
 878        return found;
 879}
 880
 881/*
 882 * The return value of `check_changes_tracked_files()` can be:
 883 *
 884 * < 0 if there was an error
 885 * = 0 if there are no changes.
 886 * > 0 if there are changes.
 887 */
 888static int check_changes_tracked_files(struct pathspec ps)
 889{
 890        int result;
 891        struct rev_info rev;
 892        struct object_id dummy;
 893
 894        /* No initial commit. */
 895        if (get_oid("HEAD", &dummy))
 896                return -1;
 897
 898        if (read_cache() < 0)
 899                return -1;
 900
 901        init_revisions(&rev, NULL);
 902        rev.prune_data = ps;
 903
 904        rev.diffopt.flags.quick = 1;
 905        rev.diffopt.flags.ignore_submodules = 1;
 906        rev.abbrev = 0;
 907
 908        add_head_to_pending(&rev);
 909        diff_setup_done(&rev.diffopt);
 910
 911        result = run_diff_index(&rev, 1);
 912        if (diff_result_code(&rev.diffopt, result))
 913                return 1;
 914
 915        object_array_clear(&rev.pending);
 916        result = run_diff_files(&rev, 0);
 917        if (diff_result_code(&rev.diffopt, result))
 918                return 1;
 919
 920        return 0;
 921}
 922
 923/*
 924 * The function will fill `untracked_files` with the names of untracked files
 925 * It will return 1 if there were any changes and 0 if there were not.
 926 */
 927static int check_changes(struct pathspec ps, int include_untracked,
 928                         struct strbuf *untracked_files)
 929{
 930        int ret = 0;
 931        if (check_changes_tracked_files(ps))
 932                ret = 1;
 933
 934        if (include_untracked && get_untracked_files(ps, include_untracked,
 935                                                     untracked_files))
 936                ret = 1;
 937
 938        return ret;
 939}
 940
 941static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
 942                                struct strbuf files)
 943{
 944        int ret = 0;
 945        struct strbuf untracked_msg = STRBUF_INIT;
 946        struct strbuf out = STRBUF_INIT;
 947        struct child_process cp_upd_index = CHILD_PROCESS_INIT;
 948        struct child_process cp_write_tree = CHILD_PROCESS_INIT;
 949
 950        cp_upd_index.git_cmd = 1;
 951        argv_array_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
 952                         "--remove", "--stdin", NULL);
 953        argv_array_pushf(&cp_upd_index.env_array, "GIT_INDEX_FILE=%s",
 954                         stash_index_path.buf);
 955
 956        strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
 957        if (pipe_command(&cp_upd_index, files.buf, files.len, NULL, 0,
 958                         NULL, 0)) {
 959                ret = -1;
 960                goto done;
 961        }
 962
 963        cp_write_tree.git_cmd = 1;
 964        argv_array_push(&cp_write_tree.args, "write-tree");
 965        argv_array_pushf(&cp_write_tree.env_array, "GIT_INDEX_FILE=%s",
 966                         stash_index_path.buf);
 967        if (pipe_command(&cp_write_tree, NULL, 0, &out, 0,NULL, 0)) {
 968                ret = -1;
 969                goto done;
 970        }
 971        get_oid_hex(out.buf, &info->u_tree);
 972
 973        if (commit_tree(untracked_msg.buf, untracked_msg.len,
 974                        &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
 975                ret = -1;
 976                goto done;
 977        }
 978
 979done:
 980        strbuf_release(&untracked_msg);
 981        strbuf_release(&out);
 982        remove_path(stash_index_path.buf);
 983        return ret;
 984}
 985
 986static int stash_patch(struct stash_info *info, struct pathspec ps,
 987                       struct strbuf *out_patch, int quiet)
 988{
 989        int ret = 0;
 990        struct strbuf out = STRBUF_INIT;
 991        struct child_process cp_read_tree = CHILD_PROCESS_INIT;
 992        struct child_process cp_add_i = CHILD_PROCESS_INIT;
 993        struct child_process cp_write_tree = CHILD_PROCESS_INIT;
 994        struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
 995
 996        remove_path(stash_index_path.buf);
 997
 998        cp_read_tree.git_cmd = 1;
 999        argv_array_pushl(&cp_read_tree.args, "read-tree", "HEAD", NULL);
1000        argv_array_pushf(&cp_read_tree.env_array, "GIT_INDEX_FILE=%s",
1001                         stash_index_path.buf);
1002        if (run_command(&cp_read_tree)) {
1003                ret = -1;
1004                goto done;
1005        }
1006
1007        /* Find out what the user wants. */
1008        cp_add_i.git_cmd = 1;
1009        argv_array_pushl(&cp_add_i.args, "add--interactive", "--patch=stash",
1010                         "--", NULL);
1011        add_pathspecs(&cp_add_i.args, ps);
1012        argv_array_pushf(&cp_add_i.env_array, "GIT_INDEX_FILE=%s",
1013                         stash_index_path.buf);
1014        if (run_command(&cp_add_i)) {
1015                ret = -1;
1016                goto done;
1017        }
1018
1019        /* State of the working tree. */
1020        cp_write_tree.git_cmd = 1;
1021        argv_array_push(&cp_write_tree.args, "write-tree");
1022        argv_array_pushf(&cp_write_tree.env_array, "GIT_INDEX_FILE=%s",
1023                         stash_index_path.buf);
1024        if (pipe_command(&cp_write_tree, NULL, 0, &out, 0,NULL, 0)) {
1025                ret = -1;
1026                goto done;
1027        }
1028
1029        get_oid_hex(out.buf, &info->w_tree);
1030
1031        cp_diff_tree.git_cmd = 1;
1032        argv_array_pushl(&cp_diff_tree.args, "diff-tree", "-p", "HEAD",
1033                         oid_to_hex(&info->w_tree), "--", NULL);
1034        if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1035                ret = -1;
1036                goto done;
1037        }
1038
1039        if (!out_patch->len) {
1040                if (!quiet)
1041                        fprintf_ln(stderr, _("No changes selected"));
1042                ret = 1;
1043        }
1044
1045done:
1046        strbuf_release(&out);
1047        remove_path(stash_index_path.buf);
1048        return ret;
1049}
1050
1051static int stash_working_tree(struct stash_info *info, struct pathspec ps)
1052{
1053        int ret = 0;
1054        struct rev_info rev;
1055        struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1056        struct child_process cp_write_tree = CHILD_PROCESS_INIT;
1057        struct strbuf out = STRBUF_INIT;
1058        struct strbuf diff_output = STRBUF_INIT;
1059
1060        init_revisions(&rev, NULL);
1061
1062        set_alternate_index_output(stash_index_path.buf);
1063        if (reset_tree(&info->i_tree, 0, 0)) {
1064                ret = -1;
1065                goto done;
1066        }
1067        set_alternate_index_output(NULL);
1068
1069        rev.prune_data = ps;
1070        rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1071        rev.diffopt.format_callback = add_diff_to_buf;
1072        rev.diffopt.format_callback_data = &diff_output;
1073
1074        if (read_cache_preload(&rev.diffopt.pathspec) < 0) {
1075                ret = -1;
1076                goto done;
1077        }
1078
1079        add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1080                           "");
1081        if (run_diff_index(&rev, 0)) {
1082                ret = -1;
1083                goto done;
1084        }
1085
1086        cp_upd_index.git_cmd = 1;
1087        argv_array_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
1088                         "--remove", "--stdin", NULL);
1089        argv_array_pushf(&cp_upd_index.env_array, "GIT_INDEX_FILE=%s",
1090                         stash_index_path.buf);
1091
1092        if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1093                         NULL, 0, NULL, 0)) {
1094                ret = -1;
1095                goto done;
1096        }
1097
1098        cp_write_tree.git_cmd = 1;
1099        argv_array_push(&cp_write_tree.args, "write-tree");
1100        argv_array_pushf(&cp_write_tree.env_array, "GIT_INDEX_FILE=%s",
1101                         stash_index_path.buf);
1102        if (pipe_command(&cp_write_tree, NULL, 0, &out, 0,NULL, 0)) {
1103                ret = -1;
1104                goto done;
1105        }
1106
1107        get_oid_hex(out.buf, &info->w_tree);
1108
1109done:
1110        UNLEAK(rev);
1111        strbuf_release(&out);
1112        object_array_clear(&rev.pending);
1113        strbuf_release(&diff_output);
1114        remove_path(stash_index_path.buf);
1115        return ret;
1116}
1117
1118static int do_create_stash(struct pathspec ps, struct strbuf *stash_msg_buf,
1119                           int include_untracked, int patch_mode,
1120                           struct stash_info *info, struct strbuf *patch,
1121                           int quiet)
1122{
1123        int ret = 0;
1124        int flags = 0;
1125        int untracked_commit_option = 0;
1126        const char *head_short_sha1 = NULL;
1127        const char *branch_ref = NULL;
1128        const char *branch_name = "(no branch)";
1129        struct commit *head_commit = NULL;
1130        struct commit_list *parents = NULL;
1131        struct strbuf msg = STRBUF_INIT;
1132        struct strbuf commit_tree_label = STRBUF_INIT;
1133        struct strbuf untracked_files = STRBUF_INIT;
1134
1135        prepare_fallback_ident("git stash", "git@stash");
1136
1137        read_cache_preload(NULL);
1138        refresh_cache(REFRESH_QUIET);
1139
1140        if (get_oid("HEAD", &info->b_commit)) {
1141                if (!quiet)
1142                        fprintf_ln(stderr, _("You do not have "
1143                                             "the initial commit yet"));
1144                ret = -1;
1145                goto done;
1146        } else {
1147                head_commit = lookup_commit(the_repository, &info->b_commit);
1148        }
1149
1150        if (!check_changes(ps, include_untracked, &untracked_files)) {
1151                ret = 1;
1152                goto done;
1153        }
1154
1155        branch_ref = resolve_ref_unsafe("HEAD", 0, NULL, &flags);
1156        if (flags & REF_ISSYMREF)
1157                branch_name = strrchr(branch_ref, '/') + 1;
1158        head_short_sha1 = find_unique_abbrev(&head_commit->object.oid,
1159                                             DEFAULT_ABBREV);
1160        strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1161        pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1162
1163        strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1164        commit_list_insert(head_commit, &parents);
1165        if (write_cache_as_tree(&info->i_tree, 0, NULL) ||
1166            commit_tree(commit_tree_label.buf, commit_tree_label.len,
1167                        &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1168                if (!quiet)
1169                        fprintf_ln(stderr, _("Cannot save the current "
1170                                             "index state"));
1171                ret = -1;
1172                goto done;
1173        }
1174
1175        if (include_untracked) {
1176                if (save_untracked_files(info, &msg, untracked_files)) {
1177                        if (!quiet)
1178                                fprintf_ln(stderr, _("Cannot save "
1179                                                     "the untracked files"));
1180                        ret = -1;
1181                        goto done;
1182                }
1183                untracked_commit_option = 1;
1184        }
1185        if (patch_mode) {
1186                ret = stash_patch(info, ps, patch, quiet);
1187                if (ret < 0) {
1188                        if (!quiet)
1189                                fprintf_ln(stderr, _("Cannot save the current "
1190                                                     "worktree state"));
1191                        goto done;
1192                } else if (ret > 0) {
1193                        goto done;
1194                }
1195        } else {
1196                if (stash_working_tree(info, ps)) {
1197                        if (!quiet)
1198                                fprintf_ln(stderr, _("Cannot save the current "
1199                                                     "worktree state"));
1200                        ret = -1;
1201                        goto done;
1202                }
1203        }
1204
1205        if (!stash_msg_buf->len)
1206                strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1207        else
1208                strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1209
1210        /*
1211         * `parents` will be empty after calling `commit_tree()`, so there is
1212         * no need to call `free_commit_list()`
1213         */
1214        parents = NULL;
1215        if (untracked_commit_option)
1216                commit_list_insert(lookup_commit(the_repository,
1217                                                 &info->u_commit),
1218                                   &parents);
1219        commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1220                           &parents);
1221        commit_list_insert(head_commit, &parents);
1222
1223        if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1224                        parents, &info->w_commit, NULL, NULL)) {
1225                if (!quiet)
1226                        fprintf_ln(stderr, _("Cannot record "
1227                                             "working tree state"));
1228                ret = -1;
1229                goto done;
1230        }
1231
1232done:
1233        strbuf_release(&commit_tree_label);
1234        strbuf_release(&msg);
1235        strbuf_release(&untracked_files);
1236        return ret;
1237}
1238
1239static int create_stash(int argc, const char **argv, const char *prefix)
1240{
1241        int include_untracked = 0;
1242        int ret = 0;
1243        const char *stash_msg = NULL;
1244        struct strbuf stash_msg_buf = STRBUF_INIT;
1245        struct stash_info info;
1246        struct pathspec ps;
1247        struct option options[] = {
1248                OPT_BOOL('u', "include-untracked", &include_untracked,
1249                         N_("include untracked files in stash")),
1250                OPT_STRING('m', "message", &stash_msg, N_("message"),
1251                         N_("stash message")),
1252                OPT_END()
1253        };
1254
1255        argc = parse_options(argc, argv, prefix, options,
1256                             git_stash_helper_create_usage,
1257                             0);
1258
1259        memset(&ps, 0, sizeof(ps));
1260        if (!check_changes_tracked_files(ps))
1261                return 0;
1262
1263        strbuf_addstr(&stash_msg_buf, stash_msg);
1264        ret = do_create_stash(ps, &stash_msg_buf, include_untracked, 0, &info,
1265                              NULL, 0);
1266        if (!ret)
1267                printf_ln("%s", oid_to_hex(&info.w_commit));
1268
1269        strbuf_release(&stash_msg_buf);
1270        return ret;
1271}
1272
1273static int do_push_stash(struct pathspec ps, const char *stash_msg, int quiet,
1274                         int keep_index, int patch_mode, int include_untracked)
1275{
1276        int ret = 0;
1277        struct stash_info info;
1278        struct strbuf patch = STRBUF_INIT;
1279        struct strbuf stash_msg_buf = STRBUF_INIT;
1280        struct strbuf untracked_files = STRBUF_INIT;
1281
1282        if (patch_mode && keep_index == -1)
1283                keep_index = 1;
1284
1285        if (patch_mode && include_untracked) {
1286                fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1287                                     " or --all at the same time"));
1288                ret = -1;
1289                goto done;
1290        }
1291
1292        read_cache_preload(NULL);
1293        if (!include_untracked && ps.nr) {
1294                int i;
1295                char *ps_matched = xcalloc(ps.nr, 1);
1296
1297                for (i = 0; i < active_nr; i++)
1298                        ce_path_match(&the_index, active_cache[i], &ps,
1299                                      ps_matched);
1300
1301                if (report_path_error(ps_matched, &ps, NULL)) {
1302                        fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1303                        ret = -1;
1304                        free(ps_matched);
1305                        goto done;
1306                }
1307                free(ps_matched);
1308        }
1309
1310        if (refresh_cache(REFRESH_QUIET)) {
1311                ret = -1;
1312                goto done;
1313        }
1314
1315        if (!check_changes(ps, include_untracked, &untracked_files)) {
1316                if (!quiet)
1317                        printf_ln(_("No local changes to save"));
1318                goto done;
1319        }
1320
1321        if (!reflog_exists(ref_stash) && do_clear_stash()) {
1322                ret = -1;
1323                if (!quiet)
1324                        fprintf_ln(stderr, _("Cannot initialize stash"));
1325                goto done;
1326        }
1327
1328        if (stash_msg)
1329                strbuf_addstr(&stash_msg_buf, stash_msg);
1330        if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode,
1331                            &info, &patch, quiet)) {
1332                ret = -1;
1333                goto done;
1334        }
1335
1336        if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1337                ret = -1;
1338                if (!quiet)
1339                        fprintf_ln(stderr, _("Cannot save the current status"));
1340                goto done;
1341        }
1342
1343        if (!quiet)
1344                printf_ln(_("Saved working directory and index state %s"),
1345                          stash_msg_buf.buf);
1346
1347        if (!patch_mode) {
1348                if (include_untracked && !ps.nr) {
1349                        struct child_process cp = CHILD_PROCESS_INIT;
1350
1351                        cp.git_cmd = 1;
1352                        argv_array_pushl(&cp.args, "clean", "--force",
1353                                         "--quiet", "-d", NULL);
1354                        if (include_untracked == INCLUDE_ALL_FILES)
1355                                argv_array_push(&cp.args, "-x");
1356                        if (run_command(&cp)) {
1357                                ret = -1;
1358                                goto done;
1359                        }
1360                }
1361                discard_cache();
1362                if (ps.nr) {
1363                        struct child_process cp_add = CHILD_PROCESS_INIT;
1364                        struct child_process cp_diff = CHILD_PROCESS_INIT;
1365                        struct child_process cp_apply = CHILD_PROCESS_INIT;
1366                        struct strbuf out = STRBUF_INIT;
1367
1368                        cp_add.git_cmd = 1;
1369                        argv_array_push(&cp_add.args, "add");
1370                        if (!include_untracked)
1371                                argv_array_push(&cp_add.args, "-u");
1372                        if (include_untracked == INCLUDE_ALL_FILES)
1373                                argv_array_push(&cp_add.args, "--force");
1374                        argv_array_push(&cp_add.args, "--");
1375                        add_pathspecs(&cp_add.args, ps);
1376                        if (run_command(&cp_add)) {
1377                                ret = -1;
1378                                goto done;
1379                        }
1380
1381                        cp_diff.git_cmd = 1;
1382                        argv_array_pushl(&cp_diff.args, "diff-index", "-p",
1383                                         "--cached", "--binary", "HEAD", "--",
1384                                         NULL);
1385                        add_pathspecs(&cp_diff.args, ps);
1386                        if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1387                                ret = -1;
1388                                goto done;
1389                        }
1390
1391                        cp_apply.git_cmd = 1;
1392                        argv_array_pushl(&cp_apply.args, "apply", "--index",
1393                                         "-R", NULL);
1394                        if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1395                                         NULL, 0)) {
1396                                ret = -1;
1397                                goto done;
1398                        }
1399                } else {
1400                        struct child_process cp = CHILD_PROCESS_INIT;
1401                        cp.git_cmd = 1;
1402                        argv_array_pushl(&cp.args, "reset", "--hard", "-q",
1403                                         NULL);
1404                        if (run_command(&cp)) {
1405                                ret = -1;
1406                                goto done;
1407                        }
1408                }
1409
1410                if (keep_index == 1 && !is_null_oid(&info.i_tree)) {
1411                        struct child_process cp_ls = CHILD_PROCESS_INIT;
1412                        struct child_process cp_checkout = CHILD_PROCESS_INIT;
1413                        struct strbuf out = STRBUF_INIT;
1414
1415                        if (reset_tree(&info.i_tree, 0, 1)) {
1416                                ret = -1;
1417                                goto done;
1418                        }
1419
1420                        cp_ls.git_cmd = 1;
1421                        argv_array_pushl(&cp_ls.args, "ls-files", "-z",
1422                                         "--modified", "--", NULL);
1423
1424                        add_pathspecs(&cp_ls.args, ps);
1425                        if (pipe_command(&cp_ls, NULL, 0, &out, 0, NULL, 0)) {
1426                                ret = -1;
1427                                goto done;
1428                        }
1429
1430                        cp_checkout.git_cmd = 1;
1431                        argv_array_pushl(&cp_checkout.args, "checkout-index",
1432                                         "-z", "--force", "--stdin", NULL);
1433                        if (pipe_command(&cp_checkout, out.buf, out.len, NULL,
1434                                         0, NULL, 0)) {
1435                                ret = -1;
1436                                goto done;
1437                        }
1438                }
1439                goto done;
1440        } else {
1441                struct child_process cp = CHILD_PROCESS_INIT;
1442
1443                cp.git_cmd = 1;
1444                argv_array_pushl(&cp.args, "apply", "-R", NULL);
1445
1446                if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1447                        if (!quiet)
1448                                fprintf_ln(stderr, _("Cannot remove "
1449                                                     "worktree changes"));
1450                        ret = -1;
1451                        goto done;
1452                }
1453
1454                if (keep_index < 1) {
1455                        struct child_process cp = CHILD_PROCESS_INIT;
1456
1457                        cp.git_cmd = 1;
1458                        argv_array_pushl(&cp.args, "reset", "-q", "--", NULL);
1459                        add_pathspecs(&cp.args, ps);
1460                        if (run_command(&cp)) {
1461                                ret = -1;
1462                                goto done;
1463                        }
1464                }
1465                goto done;
1466        }
1467
1468done:
1469        strbuf_release(&stash_msg_buf);
1470        return ret;
1471}
1472
1473static int push_stash(int argc, const char **argv, const char *prefix)
1474{
1475        int keep_index = -1;
1476        int patch_mode = 0;
1477        int include_untracked = 0;
1478        int quiet = 0;
1479        const char *stash_msg = NULL;
1480        struct pathspec ps;
1481        struct option options[] = {
1482                OPT_BOOL('k', "keep-index", &keep_index,
1483                         N_("keep index")),
1484                OPT_BOOL('p', "patch", &patch_mode,
1485                         N_("stash in patch mode")),
1486                OPT__QUIET(&quiet, N_("quiet mode")),
1487                OPT_BOOL('u', "include-untracked", &include_untracked,
1488                         N_("include untracked files in stash")),
1489                OPT_SET_INT('a', "all", &include_untracked,
1490                            N_("include ignore files"), 2),
1491                OPT_STRING('m', "message", &stash_msg, N_("message"),
1492                           N_("stash message")),
1493                OPT_END()
1494        };
1495
1496        argc = parse_options(argc, argv, prefix, options,
1497                             git_stash_helper_push_usage,
1498                             0);
1499
1500        parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL, prefix, argv);
1501        return do_push_stash(ps, stash_msg, quiet, keep_index, patch_mode,
1502                             include_untracked);
1503}
1504
1505static int save_stash(int argc, const char **argv, const char *prefix)
1506{
1507        int keep_index = -1;
1508        int patch_mode = 0;
1509        int include_untracked = 0;
1510        int quiet = 0;
1511        int ret = 0;
1512        const char *stash_msg = NULL;
1513        struct pathspec ps;
1514        struct strbuf stash_msg_buf = STRBUF_INIT;
1515        struct option options[] = {
1516                OPT_BOOL('k', "keep-index", &keep_index,
1517                         N_("keep index")),
1518                OPT_BOOL('p', "patch", &patch_mode,
1519                         N_("stash in patch mode")),
1520                OPT__QUIET(&quiet, N_("quiet mode")),
1521                OPT_BOOL('u', "include-untracked", &include_untracked,
1522                         N_("include untracked files in stash")),
1523                OPT_SET_INT('a', "all", &include_untracked,
1524                            N_("include ignore files"), 2),
1525                OPT_STRING('m', "message", &stash_msg, "message",
1526                           N_("stash message")),
1527                OPT_END()
1528        };
1529
1530        argc = parse_options(argc, argv, prefix, options,
1531                             git_stash_helper_save_usage,
1532                             PARSE_OPT_KEEP_DASHDASH);
1533
1534        if (argc)
1535                stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
1536
1537        memset(&ps, 0, sizeof(ps));
1538        ret = do_push_stash(ps, stash_msg, quiet, keep_index,
1539                            patch_mode, include_untracked);
1540
1541        strbuf_release(&stash_msg_buf);
1542        return ret;
1543}
1544
1545int cmd_stash__helper(int argc, const char **argv, const char *prefix)
1546{
1547        pid_t pid = getpid();
1548        const char *index_file;
1549
1550        struct option options[] = {
1551                OPT_END()
1552        };
1553
1554        git_config(git_diff_basic_config, NULL);
1555
1556        argc = parse_options(argc, argv, prefix, options, git_stash_helper_usage,
1557                             PARSE_OPT_KEEP_UNKNOWN | PARSE_OPT_KEEP_DASHDASH);
1558
1559        index_file = get_index_file();
1560        strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
1561                    (uintmax_t)pid);
1562
1563        if (argc < 1)
1564                usage_with_options(git_stash_helper_usage, options);
1565        if (!strcmp(argv[0], "apply"))
1566                return !!apply_stash(argc, argv, prefix);
1567        else if (!strcmp(argv[0], "clear"))
1568                return !!clear_stash(argc, argv, prefix);
1569        else if (!strcmp(argv[0], "drop"))
1570                return !!drop_stash(argc, argv, prefix);
1571        else if (!strcmp(argv[0], "pop"))
1572                return !!pop_stash(argc, argv, prefix);
1573        else if (!strcmp(argv[0], "branch"))
1574                return !!branch_stash(argc, argv, prefix);
1575        else if (!strcmp(argv[0], "list"))
1576                return !!list_stash(argc, argv, prefix);
1577        else if (!strcmp(argv[0], "show"))
1578                return !!show_stash(argc, argv, prefix);
1579        else if (!strcmp(argv[0], "store"))
1580                return !!store_stash(argc, argv, prefix);
1581        else if (!strcmp(argv[0], "create"))
1582                return !!create_stash(argc, argv, prefix);
1583        else if (!strcmp(argv[0], "push"))
1584                return !!push_stash(argc, argv, prefix);
1585        else if (!strcmp(argv[0], "save"))
1586                return !!save_stash(argc, argv, prefix);
1587
1588        usage_msg_opt(xstrfmt(_("unknown subcommand: %s"), argv[0]),
1589                      git_stash_helper_usage, options);
1590}