t4000-t4999: detect and signal failure within loop
[git/debian.git] / builtin / stash.c
blob18c812bbe032cc24e57bd3083822bb4753dfa1ca
1 #define USE_THE_INDEX_COMPATIBILITY_MACROS
2 #include "builtin.h"
3 #include "config.h"
4 #include "parse-options.h"
5 #include "refs.h"
6 #include "lockfile.h"
7 #include "cache-tree.h"
8 #include "unpack-trees.h"
9 #include "merge-recursive.h"
10 #include "strvec.h"
11 #include "run-command.h"
12 #include "dir.h"
13 #include "entry.h"
14 #include "rerere.h"
15 #include "revision.h"
16 #include "log-tree.h"
17 #include "diffcore.h"
18 #include "exec-cmd.h"
19 #include "entry.h"
21 #define INCLUDE_ALL_FILES 2
23 static const char * const git_stash_usage[] = {
24 N_("git stash list [<options>]"),
25 N_("git stash show [<options>] [<stash>]"),
26 N_("git stash drop [-q|--quiet] [<stash>]"),
27 N_("git stash ( pop | apply ) [--index] [-q|--quiet] [<stash>]"),
28 N_("git stash branch <branchname> [<stash>]"),
29 "git stash clear",
30 N_("git stash [push [-p|--patch] [-S|--staged] [-k|--[no-]keep-index] [-q|--quiet]\n"
31 " [-u|--include-untracked] [-a|--all] [-m|--message <message>]\n"
32 " [--pathspec-from-file=<file> [--pathspec-file-nul]]\n"
33 " [--] [<pathspec>...]]"),
34 N_("git stash save [-p|--patch] [-S|--staged] [-k|--[no-]keep-index] [-q|--quiet]\n"
35 " [-u|--include-untracked] [-a|--all] [<message>]"),
36 NULL
39 static const char * const git_stash_list_usage[] = {
40 N_("git stash list [<options>]"),
41 NULL
44 static const char * const git_stash_show_usage[] = {
45 N_("git stash show [<options>] [<stash>]"),
46 NULL
49 static const char * const git_stash_drop_usage[] = {
50 N_("git stash drop [-q|--quiet] [<stash>]"),
51 NULL
54 static const char * const git_stash_pop_usage[] = {
55 N_("git stash pop [--index] [-q|--quiet] [<stash>]"),
56 NULL
59 static const char * const git_stash_apply_usage[] = {
60 N_("git stash apply [--index] [-q|--quiet] [<stash>]"),
61 NULL
64 static const char * const git_stash_branch_usage[] = {
65 N_("git stash branch <branchname> [<stash>]"),
66 NULL
69 static const char * const git_stash_clear_usage[] = {
70 "git stash clear",
71 NULL
74 static const char * const git_stash_store_usage[] = {
75 N_("git stash store [-m|--message <message>] [-q|--quiet] <commit>"),
76 NULL
79 static const char * const git_stash_push_usage[] = {
80 N_("git stash [push [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
81 " [-u|--include-untracked] [-a|--all] [-m|--message <message>]\n"
82 " [--] [<pathspec>...]]"),
83 NULL
86 static const char * const git_stash_save_usage[] = {
87 N_("git stash save [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
88 " [-u|--include-untracked] [-a|--all] [<message>]"),
89 NULL
92 static const char ref_stash[] = "refs/stash";
93 static struct strbuf stash_index_path = STRBUF_INIT;
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
105 struct 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;
119 static void free_stash_info(struct stash_info *info)
121 strbuf_release(&info->revision);
124 static void assert_stash_like(struct stash_info *info, const char *revision)
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);
133 static int get_stash_info(struct stash_info *info, int argc, const char **argv)
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;
143 if (argc > 1) {
144 int i;
145 struct strbuf refs_msg = STRBUF_INIT;
147 for (i = 0; i < argc; i++)
148 strbuf_addf(&refs_msg, " '%s'", argv[i]);
150 fprintf_ln(stderr, _("Too many revisions specified:%s"),
151 refs_msg.buf);
152 strbuf_release(&refs_msg);
154 return -1;
157 if (argc == 1)
158 commit = argv[0];
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;
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);
175 revision = info->revision.buf;
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;
183 assert_stash_like(info, revision);
185 info->has_u = !get_oidf(&info->u_tree, "%s^3:", revision);
187 end_of_rev = strchrnul(revision, '@');
188 strbuf_add(&symbolic, revision, end_of_rev - revision);
190 ret = dwim_ref(symbolic.buf, symbolic.len, &dummy, &expanded_ref, 0);
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);
203 free(expanded_ref);
204 return !(ret == 0 || ret == 1);
207 static int do_clear_stash(void)
209 struct object_id obj;
210 if (get_oid(ref_stash, &obj))
211 return 0;
213 return delete_ref(NULL, ref_stash, &obj, 0);
216 static int clear_stash(int argc, const char **argv, const char *prefix)
218 struct option options[] = {
219 OPT_END()
222 argc = parse_options(argc, argv, prefix, options,
223 git_stash_clear_usage,
224 PARSE_OPT_STOP_AT_NON_OPTION);
226 if (argc)
227 return error(_("git stash clear with arguments is "
228 "unimplemented"));
230 return do_clear_stash();
233 static int reset_tree(struct object_id *i_tree, int update, int reset)
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;
241 read_cache_preload(NULL);
242 if (refresh_cache(REFRESH_QUIET))
243 return -1;
245 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
247 memset(&opts, 0, sizeof(opts));
249 tree = parse_tree_indirect(i_tree);
250 if (parse_tree(tree))
251 return -1;
253 init_tree_desc(t, tree->buffer, tree->size);
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 ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
260 opts.update = update;
261 if (update)
262 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
263 opts.fn = oneway_merge;
265 if (unpack_trees(nr_trees, t, &opts))
266 return -1;
268 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
269 return error(_("unable to write new index file"));
271 return 0;
274 static int diff_tree_binary(struct strbuf *out, struct object_id *w_commit)
276 struct child_process cp = CHILD_PROCESS_INIT;
277 const char *w_commit_hex = oid_to_hex(w_commit);
280 * Diff-tree would not be very hard to replace with a native function,
281 * however it should be done together with apply_cached.
283 cp.git_cmd = 1;
284 strvec_pushl(&cp.args, "diff-tree", "--binary", NULL);
285 strvec_pushf(&cp.args, "%s^2^..%s^2", w_commit_hex, w_commit_hex);
287 return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
290 static int apply_cached(struct strbuf *out)
292 struct child_process cp = CHILD_PROCESS_INIT;
295 * Apply currently only reads either from stdin or a file, thus
296 * apply_all_patches would have to be updated to optionally take a
297 * buffer.
299 cp.git_cmd = 1;
300 strvec_pushl(&cp.args, "apply", "--cached", NULL);
301 return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
304 static int reset_head(void)
306 struct child_process cp = CHILD_PROCESS_INIT;
309 * Reset is overall quite simple, however there is no current public
310 * API for resetting.
312 cp.git_cmd = 1;
313 strvec_push(&cp.args, "reset");
315 return run_command(&cp);
318 static int is_path_a_directory(const char *path)
321 * This function differs from abspath.c:is_directory() in that
322 * here we use lstat() instead of stat(); we do not want to
323 * follow symbolic links here.
325 struct stat st;
326 return (!lstat(path, &st) && S_ISDIR(st.st_mode));
329 static void add_diff_to_buf(struct diff_queue_struct *q,
330 struct diff_options *options,
331 void *data)
333 int i;
335 for (i = 0; i < q->nr; i++) {
336 if (is_path_a_directory(q->queue[i]->one->path))
337 continue;
339 strbuf_addstr(data, q->queue[i]->one->path);
341 /* NUL-terminate: will be fed to update-index -z */
342 strbuf_addch(data, '\0');
346 static int restore_untracked(struct object_id *u_tree)
348 int res;
349 struct child_process cp = CHILD_PROCESS_INIT;
352 * We need to run restore files from a given index, but without
353 * affecting the current index, so we use GIT_INDEX_FILE with
354 * run_command to fork processes that will not interfere.
356 cp.git_cmd = 1;
357 strvec_push(&cp.args, "read-tree");
358 strvec_push(&cp.args, oid_to_hex(u_tree));
359 strvec_pushf(&cp.env_array, "GIT_INDEX_FILE=%s",
360 stash_index_path.buf);
361 if (run_command(&cp)) {
362 remove_path(stash_index_path.buf);
363 return -1;
366 child_process_init(&cp);
367 cp.git_cmd = 1;
368 strvec_pushl(&cp.args, "checkout-index", "--all", NULL);
369 strvec_pushf(&cp.env_array, "GIT_INDEX_FILE=%s",
370 stash_index_path.buf);
372 res = run_command(&cp);
373 remove_path(stash_index_path.buf);
374 return res;
377 static void unstage_changes_unless_new(struct object_id *orig_tree)
380 * When we enter this function, there has been a clean merge of
381 * relevant trees, and the merge logic always stages whatever merges
382 * cleanly. We want to unstage those changes, unless it corresponds
383 * to a file that didn't exist as of orig_tree.
385 * However, if any SKIP_WORKTREE path is modified relative to
386 * orig_tree, then we want to clear the SKIP_WORKTREE bit and write
387 * it to the worktree before unstaging.
390 struct checkout state = CHECKOUT_INIT;
391 struct diff_options diff_opts;
392 struct lock_file lock = LOCK_INIT;
393 int i;
395 /* If any entries have skip_worktree set, we'll have to check 'em out */
396 state.force = 1;
397 state.quiet = 1;
398 state.refresh_cache = 1;
399 state.istate = &the_index;
402 * Step 1: get a difference between orig_tree (which corresponding
403 * to the index before a merge was run) and the current index
404 * (reflecting the changes brought in by the merge).
406 diff_setup(&diff_opts);
407 diff_opts.flags.recursive = 1;
408 diff_opts.detect_rename = 0;
409 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
410 diff_setup_done(&diff_opts);
412 do_diff_cache(orig_tree, &diff_opts);
413 diffcore_std(&diff_opts);
415 /* Iterate over the paths that changed due to the merge... */
416 for (i = 0; i < diff_queued_diff.nr; i++) {
417 struct diff_filepair *p;
418 struct cache_entry *ce;
419 int pos;
421 /* Look up the path's position in the current index. */
422 p = diff_queued_diff.queue[i];
423 pos = index_name_pos(&the_index, p->two->path,
424 strlen(p->two->path));
427 * Step 2: Place changes in the working tree
429 * Stash is about restoring changes *to the working tree*.
430 * So if the merge successfully got a new version of some
431 * path, but left it out of the working tree, then clear the
432 * SKIP_WORKTREE bit and write it to the working tree.
434 if (pos >= 0 && ce_skip_worktree(active_cache[pos])) {
435 struct stat st;
437 ce = active_cache[pos];
438 if (!lstat(ce->name, &st)) {
439 /* Conflicting path present; relocate it */
440 struct strbuf new_path = STRBUF_INIT;
441 int fd;
443 strbuf_addf(&new_path,
444 "%s.stash.XXXXXX", ce->name);
445 fd = xmkstemp(new_path.buf);
446 close(fd);
447 printf(_("WARNING: Untracked file in way of "
448 "tracked file! Renaming\n "
449 " %s -> %s\n"
450 " to make room.\n"),
451 ce->name, new_path.buf);
452 if (rename(ce->name, new_path.buf))
453 die("Failed to move %s to %s\n",
454 ce->name, new_path.buf);
455 strbuf_release(&new_path);
457 checkout_entry(ce, &state, NULL, NULL);
458 ce->ce_flags &= ~CE_SKIP_WORKTREE;
462 * Step 3: "unstage" changes, as long as they are still tracked
464 if (p->one->oid_valid) {
466 * Path existed in orig_tree; restore index entry
467 * from that tree in order to "unstage" the changes.
469 int option = ADD_CACHE_OK_TO_REPLACE;
470 if (pos < 0)
471 option = ADD_CACHE_OK_TO_ADD;
473 ce = make_cache_entry(&the_index,
474 p->one->mode,
475 &p->one->oid,
476 p->one->path,
477 0, 0);
478 add_index_entry(&the_index, ce, option);
481 diff_flush(&diff_opts);
484 * Step 4: write the new index to disk
486 repo_hold_locked_index(the_repository, &lock, LOCK_DIE_ON_ERROR);
487 if (write_locked_index(&the_index, &lock,
488 COMMIT_LOCK | SKIP_IF_UNCHANGED))
489 die(_("Unable to write index."));
492 static int do_apply_stash(const char *prefix, struct stash_info *info,
493 int index, int quiet)
495 int ret;
496 int has_index = index;
497 struct merge_options o;
498 struct object_id c_tree;
499 struct object_id index_tree;
500 struct commit *result;
501 const struct object_id *bases[1];
503 read_cache_preload(NULL);
504 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0))
505 return -1;
507 if (write_cache_as_tree(&c_tree, 0, NULL))
508 return error(_("cannot apply a stash in the middle of a merge"));
510 if (index) {
511 if (oideq(&info->b_tree, &info->i_tree) ||
512 oideq(&c_tree, &info->i_tree)) {
513 has_index = 0;
514 } else {
515 struct strbuf out = STRBUF_INIT;
517 if (diff_tree_binary(&out, &info->w_commit)) {
518 strbuf_release(&out);
519 return error(_("could not generate diff %s^!."),
520 oid_to_hex(&info->w_commit));
523 ret = apply_cached(&out);
524 strbuf_release(&out);
525 if (ret)
526 return error(_("conflicts in index. "
527 "Try without --index."));
529 discard_cache();
530 read_cache();
531 if (write_cache_as_tree(&index_tree, 0, NULL))
532 return error(_("could not save index tree"));
534 reset_head();
535 discard_cache();
536 read_cache();
540 init_merge_options(&o, the_repository);
542 o.branch1 = "Updated upstream";
543 o.branch2 = "Stashed changes";
545 if (oideq(&info->b_tree, &c_tree))
546 o.branch1 = "Version stash was based on";
548 if (quiet)
549 o.verbosity = 0;
551 if (o.verbosity >= 3)
552 printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
554 bases[0] = &info->b_tree;
556 ret = merge_recursive_generic(&o, &c_tree, &info->w_tree, 1, bases,
557 &result);
558 if (ret) {
559 rerere(0);
561 if (index)
562 fprintf_ln(stderr, _("Index was not unstashed."));
564 return ret;
567 if (has_index) {
568 if (reset_tree(&index_tree, 0, 0))
569 return -1;
570 } else {
571 unstage_changes_unless_new(&c_tree);
574 if (info->has_u && restore_untracked(&info->u_tree))
575 return error(_("could not restore untracked files from stash"));
577 if (!quiet) {
578 struct child_process cp = CHILD_PROCESS_INIT;
581 * Status is quite simple and could be replaced with calls to
582 * wt_status in the future, but it adds complexities which may
583 * require more tests.
585 cp.git_cmd = 1;
586 cp.dir = prefix;
587 strvec_pushf(&cp.env_array, GIT_WORK_TREE_ENVIRONMENT"=%s",
588 absolute_path(get_git_work_tree()));
589 strvec_pushf(&cp.env_array, GIT_DIR_ENVIRONMENT"=%s",
590 absolute_path(get_git_dir()));
591 strvec_push(&cp.args, "status");
592 run_command(&cp);
595 return 0;
598 static int apply_stash(int argc, const char **argv, const char *prefix)
600 int ret;
601 int quiet = 0;
602 int index = 0;
603 struct stash_info info;
604 struct option options[] = {
605 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
606 OPT_BOOL(0, "index", &index,
607 N_("attempt to recreate the index")),
608 OPT_END()
611 argc = parse_options(argc, argv, prefix, options,
612 git_stash_apply_usage, 0);
614 if (get_stash_info(&info, argc, argv))
615 return -1;
617 ret = do_apply_stash(prefix, &info, index, quiet);
618 free_stash_info(&info);
619 return ret;
622 static int reject_reflog_ent(struct object_id *ooid, struct object_id *noid,
623 const char *email, timestamp_t timestamp, int tz,
624 const char *message, void *cb_data)
626 return 1;
629 static int reflog_is_empty(const char *refname)
631 return !for_each_reflog_ent(refname, reject_reflog_ent, NULL);
634 static int do_drop_stash(struct stash_info *info, int quiet)
636 int ret;
637 struct child_process cp_reflog = CHILD_PROCESS_INIT;
640 * reflog does not provide a simple function for deleting refs. One will
641 * need to be added to avoid implementing too much reflog code here
644 cp_reflog.git_cmd = 1;
645 strvec_pushl(&cp_reflog.args, "reflog", "delete", "--updateref",
646 "--rewrite", NULL);
647 strvec_push(&cp_reflog.args, info->revision.buf);
648 ret = run_command(&cp_reflog);
649 if (!ret) {
650 if (!quiet)
651 printf_ln(_("Dropped %s (%s)"), info->revision.buf,
652 oid_to_hex(&info->w_commit));
653 } else {
654 return error(_("%s: Could not drop stash entry"),
655 info->revision.buf);
658 if (reflog_is_empty(ref_stash))
659 do_clear_stash();
661 return 0;
664 static void assert_stash_ref(struct stash_info *info)
666 if (!info->is_stash_ref) {
667 error(_("'%s' is not a stash reference"), info->revision.buf);
668 free_stash_info(info);
669 exit(1);
673 static int drop_stash(int argc, const char **argv, const char *prefix)
675 int ret;
676 int quiet = 0;
677 struct stash_info info;
678 struct option options[] = {
679 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
680 OPT_END()
683 argc = parse_options(argc, argv, prefix, options,
684 git_stash_drop_usage, 0);
686 if (get_stash_info(&info, argc, argv))
687 return -1;
689 assert_stash_ref(&info);
691 ret = do_drop_stash(&info, quiet);
692 free_stash_info(&info);
693 return ret;
696 static int pop_stash(int argc, const char **argv, const char *prefix)
698 int ret;
699 int index = 0;
700 int quiet = 0;
701 struct stash_info info;
702 struct option options[] = {
703 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
704 OPT_BOOL(0, "index", &index,
705 N_("attempt to recreate the index")),
706 OPT_END()
709 argc = parse_options(argc, argv, prefix, options,
710 git_stash_pop_usage, 0);
712 if (get_stash_info(&info, argc, argv))
713 return -1;
715 assert_stash_ref(&info);
716 if ((ret = do_apply_stash(prefix, &info, index, quiet)))
717 printf_ln(_("The stash entry is kept in case "
718 "you need it again."));
719 else
720 ret = do_drop_stash(&info, quiet);
722 free_stash_info(&info);
723 return ret;
726 static int branch_stash(int argc, const char **argv, const char *prefix)
728 int ret;
729 const char *branch = NULL;
730 struct stash_info info;
731 struct child_process cp = CHILD_PROCESS_INIT;
732 struct option options[] = {
733 OPT_END()
736 argc = parse_options(argc, argv, prefix, options,
737 git_stash_branch_usage, 0);
739 if (!argc) {
740 fprintf_ln(stderr, _("No branch name specified"));
741 return -1;
744 branch = argv[0];
746 if (get_stash_info(&info, argc - 1, argv + 1))
747 return -1;
749 cp.git_cmd = 1;
750 strvec_pushl(&cp.args, "checkout", "-b", NULL);
751 strvec_push(&cp.args, branch);
752 strvec_push(&cp.args, oid_to_hex(&info.b_commit));
753 ret = run_command(&cp);
754 if (!ret)
755 ret = do_apply_stash(prefix, &info, 1, 0);
756 if (!ret && info.is_stash_ref)
757 ret = do_drop_stash(&info, 0);
759 free_stash_info(&info);
761 return ret;
764 static int list_stash(int argc, const char **argv, const char *prefix)
766 struct child_process cp = CHILD_PROCESS_INIT;
767 struct option options[] = {
768 OPT_END()
771 argc = parse_options(argc, argv, prefix, options,
772 git_stash_list_usage,
773 PARSE_OPT_KEEP_UNKNOWN);
775 if (!ref_exists(ref_stash))
776 return 0;
778 cp.git_cmd = 1;
779 strvec_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
780 "--first-parent", NULL);
781 strvec_pushv(&cp.args, argv);
782 strvec_push(&cp.args, ref_stash);
783 strvec_push(&cp.args, "--");
784 return run_command(&cp);
787 static int show_stat = 1;
788 static int show_patch;
789 static int show_include_untracked;
790 static int use_legacy_stash;
792 static int git_stash_config(const char *var, const char *value, void *cb)
794 if (!strcmp(var, "stash.showstat")) {
795 show_stat = git_config_bool(var, value);
796 return 0;
798 if (!strcmp(var, "stash.showpatch")) {
799 show_patch = git_config_bool(var, value);
800 return 0;
802 if (!strcmp(var, "stash.showincludeuntracked")) {
803 show_include_untracked = git_config_bool(var, value);
804 return 0;
806 if (!strcmp(var, "stash.usebuiltin")) {
807 use_legacy_stash = !git_config_bool(var, value);
808 return 0;
810 return git_diff_basic_config(var, value, cb);
813 static void diff_include_untracked(const struct stash_info *info, struct diff_options *diff_opt)
815 const struct object_id *oid[] = { &info->w_commit, &info->u_tree };
816 struct tree *tree[ARRAY_SIZE(oid)];
817 struct tree_desc tree_desc[ARRAY_SIZE(oid)];
818 struct unpack_trees_options unpack_tree_opt = { 0 };
819 int i;
821 for (i = 0; i < ARRAY_SIZE(oid); i++) {
822 tree[i] = parse_tree_indirect(oid[i]);
823 if (parse_tree(tree[i]) < 0)
824 die(_("failed to parse tree"));
825 init_tree_desc(&tree_desc[i], tree[i]->buffer, tree[i]->size);
828 unpack_tree_opt.head_idx = -1;
829 unpack_tree_opt.src_index = &the_index;
830 unpack_tree_opt.dst_index = &the_index;
831 unpack_tree_opt.merge = 1;
832 unpack_tree_opt.fn = stash_worktree_untracked_merge;
834 if (unpack_trees(ARRAY_SIZE(tree_desc), tree_desc, &unpack_tree_opt))
835 die(_("failed to unpack trees"));
837 do_diff_cache(&info->b_commit, diff_opt);
840 static int show_stash(int argc, const char **argv, const char *prefix)
842 int i;
843 int ret = 0;
844 struct stash_info info;
845 struct rev_info rev;
846 struct strvec stash_args = STRVEC_INIT;
847 struct strvec revision_args = STRVEC_INIT;
848 enum {
849 UNTRACKED_NONE,
850 UNTRACKED_INCLUDE,
851 UNTRACKED_ONLY
852 } show_untracked = show_include_untracked ? UNTRACKED_INCLUDE : UNTRACKED_NONE;
853 struct option options[] = {
854 OPT_SET_INT('u', "include-untracked", &show_untracked,
855 N_("include untracked files in the stash"),
856 UNTRACKED_INCLUDE),
857 OPT_SET_INT_F(0, "only-untracked", &show_untracked,
858 N_("only show untracked files in the stash"),
859 UNTRACKED_ONLY, PARSE_OPT_NONEG),
860 OPT_END()
863 init_diff_ui_defaults();
864 git_config(git_diff_ui_config, NULL);
865 init_revisions(&rev, prefix);
867 argc = parse_options(argc, argv, prefix, options, git_stash_show_usage,
868 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
869 PARSE_OPT_KEEP_DASHDASH);
871 strvec_push(&revision_args, argv[0]);
872 for (i = 1; i < argc; i++) {
873 if (argv[i][0] != '-')
874 strvec_push(&stash_args, argv[i]);
875 else
876 strvec_push(&revision_args, argv[i]);
879 ret = get_stash_info(&info, stash_args.nr, stash_args.v);
880 strvec_clear(&stash_args);
881 if (ret)
882 return -1;
885 * The config settings are applied only if there are not passed
886 * any options.
888 if (revision_args.nr == 1) {
889 if (show_stat)
890 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
892 if (show_patch)
893 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
895 if (!show_stat && !show_patch) {
896 free_stash_info(&info);
897 return 0;
901 argc = setup_revisions(revision_args.nr, revision_args.v, &rev, NULL);
902 if (argc > 1) {
903 free_stash_info(&info);
904 usage_with_options(git_stash_show_usage, options);
906 if (!rev.diffopt.output_format) {
907 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
908 diff_setup_done(&rev.diffopt);
911 rev.diffopt.flags.recursive = 1;
912 setup_diff_pager(&rev.diffopt);
913 switch (show_untracked) {
914 case UNTRACKED_NONE:
915 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
916 break;
917 case UNTRACKED_ONLY:
918 if (info.has_u)
919 diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
920 break;
921 case UNTRACKED_INCLUDE:
922 if (info.has_u)
923 diff_include_untracked(&info, &rev.diffopt);
924 else
925 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
926 break;
928 log_tree_diff_flush(&rev);
930 free_stash_info(&info);
931 return diff_result_code(&rev.diffopt, 0);
934 static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
935 int quiet)
937 if (!stash_msg)
938 stash_msg = "Created via \"git stash store\".";
940 if (update_ref(stash_msg, ref_stash, w_commit, NULL,
941 REF_FORCE_CREATE_REFLOG,
942 quiet ? UPDATE_REFS_QUIET_ON_ERR :
943 UPDATE_REFS_MSG_ON_ERR)) {
944 if (!quiet) {
945 fprintf_ln(stderr, _("Cannot update %s with %s"),
946 ref_stash, oid_to_hex(w_commit));
948 return -1;
951 return 0;
954 static int store_stash(int argc, const char **argv, const char *prefix)
956 int quiet = 0;
957 const char *stash_msg = NULL;
958 struct object_id obj;
959 struct object_context dummy;
960 struct option options[] = {
961 OPT__QUIET(&quiet, N_("be quiet")),
962 OPT_STRING('m', "message", &stash_msg, "message",
963 N_("stash message")),
964 OPT_END()
967 argc = parse_options(argc, argv, prefix, options,
968 git_stash_store_usage,
969 PARSE_OPT_KEEP_UNKNOWN);
971 if (argc != 1) {
972 if (!quiet)
973 fprintf_ln(stderr, _("\"git stash store\" requires one "
974 "<commit> argument"));
975 return -1;
978 if (get_oid_with_context(the_repository,
979 argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
980 &dummy)) {
981 if (!quiet)
982 fprintf_ln(stderr, _("Cannot update %s with %s"),
983 ref_stash, argv[0]);
984 return -1;
987 return do_store_stash(&obj, stash_msg, quiet);
990 static void add_pathspecs(struct strvec *args,
991 const struct pathspec *ps) {
992 int i;
994 for (i = 0; i < ps->nr; i++)
995 strvec_push(args, ps->items[i].original);
999 * `untracked_files` will be filled with the names of untracked files.
1000 * The return value is:
1002 * = 0 if there are not any untracked files
1003 * > 0 if there are untracked files
1005 static int get_untracked_files(const struct pathspec *ps, int include_untracked,
1006 struct strbuf *untracked_files)
1008 int i;
1009 int found = 0;
1010 struct dir_struct dir = DIR_INIT;
1012 if (include_untracked != INCLUDE_ALL_FILES)
1013 setup_standard_excludes(&dir);
1015 fill_directory(&dir, the_repository->index, ps);
1016 for (i = 0; i < dir.nr; i++) {
1017 struct dir_entry *ent = dir.entries[i];
1018 found++;
1019 strbuf_addstr(untracked_files, ent->name);
1020 /* NUL-terminate: will be fed to update-index -z */
1021 strbuf_addch(untracked_files, '\0');
1024 dir_clear(&dir);
1025 return found;
1029 * The return value of `check_changes_tracked_files()` can be:
1031 * < 0 if there was an error
1032 * = 0 if there are no changes.
1033 * > 0 if there are changes.
1035 static int check_changes_tracked_files(const struct pathspec *ps)
1037 int result;
1038 struct rev_info rev;
1039 struct object_id dummy;
1040 int ret = 0;
1042 /* No initial commit. */
1043 if (get_oid("HEAD", &dummy))
1044 return -1;
1046 if (read_cache() < 0)
1047 return -1;
1049 init_revisions(&rev, NULL);
1050 copy_pathspec(&rev.prune_data, ps);
1052 rev.diffopt.flags.quick = 1;
1053 rev.diffopt.flags.ignore_submodules = 1;
1054 rev.abbrev = 0;
1056 add_head_to_pending(&rev);
1057 diff_setup_done(&rev.diffopt);
1059 result = run_diff_index(&rev, 1);
1060 if (diff_result_code(&rev.diffopt, result)) {
1061 ret = 1;
1062 goto done;
1065 object_array_clear(&rev.pending);
1066 result = run_diff_files(&rev, 0);
1067 if (diff_result_code(&rev.diffopt, result)) {
1068 ret = 1;
1069 goto done;
1072 done:
1073 clear_pathspec(&rev.prune_data);
1074 return ret;
1078 * The function will fill `untracked_files` with the names of untracked files
1079 * It will return 1 if there were any changes and 0 if there were not.
1081 static int check_changes(const struct pathspec *ps, int include_untracked,
1082 struct strbuf *untracked_files)
1084 int ret = 0;
1085 if (check_changes_tracked_files(ps))
1086 ret = 1;
1088 if (include_untracked && get_untracked_files(ps, include_untracked,
1089 untracked_files))
1090 ret = 1;
1092 return ret;
1095 static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
1096 struct strbuf files)
1098 int ret = 0;
1099 struct strbuf untracked_msg = STRBUF_INIT;
1100 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1101 struct index_state istate = { NULL };
1103 cp_upd_index.git_cmd = 1;
1104 strvec_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
1105 "--remove", "--stdin", NULL);
1106 strvec_pushf(&cp_upd_index.env_array, "GIT_INDEX_FILE=%s",
1107 stash_index_path.buf);
1109 strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
1110 if (pipe_command(&cp_upd_index, files.buf, files.len, NULL, 0,
1111 NULL, 0)) {
1112 ret = -1;
1113 goto done;
1116 if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
1117 NULL)) {
1118 ret = -1;
1119 goto done;
1122 if (commit_tree(untracked_msg.buf, untracked_msg.len,
1123 &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
1124 ret = -1;
1125 goto done;
1128 done:
1129 discard_index(&istate);
1130 strbuf_release(&untracked_msg);
1131 remove_path(stash_index_path.buf);
1132 return ret;
1135 static int stash_staged(struct stash_info *info, struct strbuf *out_patch,
1136 int quiet)
1138 int ret = 0;
1139 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1140 struct index_state istate = { NULL };
1142 if (write_index_as_tree(&info->w_tree, &istate, the_repository->index_file,
1143 0, NULL)) {
1144 ret = -1;
1145 goto done;
1148 cp_diff_tree.git_cmd = 1;
1149 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1150 oid_to_hex(&info->w_tree), "--", NULL);
1151 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1152 ret = -1;
1153 goto done;
1156 if (!out_patch->len) {
1157 if (!quiet)
1158 fprintf_ln(stderr, _("No staged changes"));
1159 ret = 1;
1162 done:
1163 discard_index(&istate);
1164 return ret;
1167 static int stash_patch(struct stash_info *info, const struct pathspec *ps,
1168 struct strbuf *out_patch, int quiet)
1170 int ret = 0;
1171 struct child_process cp_read_tree = CHILD_PROCESS_INIT;
1172 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1173 struct index_state istate = { NULL };
1174 char *old_index_env = NULL, *old_repo_index_file;
1176 remove_path(stash_index_path.buf);
1178 cp_read_tree.git_cmd = 1;
1179 strvec_pushl(&cp_read_tree.args, "read-tree", "HEAD", NULL);
1180 strvec_pushf(&cp_read_tree.env_array, "GIT_INDEX_FILE=%s",
1181 stash_index_path.buf);
1182 if (run_command(&cp_read_tree)) {
1183 ret = -1;
1184 goto done;
1187 /* Find out what the user wants. */
1188 old_repo_index_file = the_repository->index_file;
1189 the_repository->index_file = stash_index_path.buf;
1190 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
1191 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
1193 ret = run_add_interactive(NULL, "--patch=stash", ps);
1195 the_repository->index_file = old_repo_index_file;
1196 if (old_index_env && *old_index_env)
1197 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
1198 else
1199 unsetenv(INDEX_ENVIRONMENT);
1200 FREE_AND_NULL(old_index_env);
1202 /* State of the working tree. */
1203 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1204 NULL)) {
1205 ret = -1;
1206 goto done;
1209 cp_diff_tree.git_cmd = 1;
1210 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1211 oid_to_hex(&info->w_tree), "--", NULL);
1212 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1213 ret = -1;
1214 goto done;
1217 if (!out_patch->len) {
1218 if (!quiet)
1219 fprintf_ln(stderr, _("No changes selected"));
1220 ret = 1;
1223 done:
1224 discard_index(&istate);
1225 remove_path(stash_index_path.buf);
1226 return ret;
1229 static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
1231 int ret = 0;
1232 struct rev_info rev;
1233 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1234 struct strbuf diff_output = STRBUF_INIT;
1235 struct index_state istate = { NULL };
1237 init_revisions(&rev, NULL);
1238 copy_pathspec(&rev.prune_data, ps);
1240 set_alternate_index_output(stash_index_path.buf);
1241 if (reset_tree(&info->i_tree, 0, 0)) {
1242 ret = -1;
1243 goto done;
1245 set_alternate_index_output(NULL);
1247 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1248 rev.diffopt.format_callback = add_diff_to_buf;
1249 rev.diffopt.format_callback_data = &diff_output;
1251 if (read_cache_preload(&rev.diffopt.pathspec) < 0) {
1252 ret = -1;
1253 goto done;
1256 add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1257 "");
1258 if (run_diff_index(&rev, 0)) {
1259 ret = -1;
1260 goto done;
1263 cp_upd_index.git_cmd = 1;
1264 strvec_pushl(&cp_upd_index.args, "update-index",
1265 "--ignore-skip-worktree-entries",
1266 "-z", "--add", "--remove", "--stdin", NULL);
1267 strvec_pushf(&cp_upd_index.env_array, "GIT_INDEX_FILE=%s",
1268 stash_index_path.buf);
1270 if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1271 NULL, 0, NULL, 0)) {
1272 ret = -1;
1273 goto done;
1276 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1277 NULL)) {
1278 ret = -1;
1279 goto done;
1282 done:
1283 discard_index(&istate);
1284 UNLEAK(rev);
1285 object_array_clear(&rev.pending);
1286 clear_pathspec(&rev.prune_data);
1287 strbuf_release(&diff_output);
1288 remove_path(stash_index_path.buf);
1289 return ret;
1292 static int do_create_stash(const struct pathspec *ps, struct strbuf *stash_msg_buf,
1293 int include_untracked, int patch_mode, int only_staged,
1294 struct stash_info *info, struct strbuf *patch,
1295 int quiet)
1297 int ret = 0;
1298 int flags = 0;
1299 int untracked_commit_option = 0;
1300 const char *head_short_sha1 = NULL;
1301 const char *branch_ref = NULL;
1302 const char *branch_name = "(no branch)";
1303 struct commit *head_commit = NULL;
1304 struct commit_list *parents = NULL;
1305 struct strbuf msg = STRBUF_INIT;
1306 struct strbuf commit_tree_label = STRBUF_INIT;
1307 struct strbuf untracked_files = STRBUF_INIT;
1309 prepare_fallback_ident("git stash", "git@stash");
1311 read_cache_preload(NULL);
1312 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0) < 0) {
1313 ret = -1;
1314 goto done;
1317 if (get_oid("HEAD", &info->b_commit)) {
1318 if (!quiet)
1319 fprintf_ln(stderr, _("You do not have "
1320 "the initial commit yet"));
1321 ret = -1;
1322 goto done;
1323 } else {
1324 head_commit = lookup_commit(the_repository, &info->b_commit);
1327 if (!check_changes(ps, include_untracked, &untracked_files)) {
1328 ret = 1;
1329 goto done;
1332 branch_ref = resolve_ref_unsafe("HEAD", 0, NULL, &flags);
1333 if (flags & REF_ISSYMREF)
1334 branch_name = strrchr(branch_ref, '/') + 1;
1335 head_short_sha1 = find_unique_abbrev(&head_commit->object.oid,
1336 DEFAULT_ABBREV);
1337 strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1338 pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1340 strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1341 commit_list_insert(head_commit, &parents);
1342 if (write_cache_as_tree(&info->i_tree, 0, NULL) ||
1343 commit_tree(commit_tree_label.buf, commit_tree_label.len,
1344 &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1345 if (!quiet)
1346 fprintf_ln(stderr, _("Cannot save the current "
1347 "index state"));
1348 ret = -1;
1349 goto done;
1352 if (include_untracked) {
1353 if (save_untracked_files(info, &msg, untracked_files)) {
1354 if (!quiet)
1355 fprintf_ln(stderr, _("Cannot save "
1356 "the untracked files"));
1357 ret = -1;
1358 goto done;
1360 untracked_commit_option = 1;
1362 if (patch_mode) {
1363 ret = stash_patch(info, ps, patch, quiet);
1364 if (ret < 0) {
1365 if (!quiet)
1366 fprintf_ln(stderr, _("Cannot save the current "
1367 "worktree state"));
1368 goto done;
1369 } else if (ret > 0) {
1370 goto done;
1372 } else if (only_staged) {
1373 ret = stash_staged(info, patch, quiet);
1374 if (ret < 0) {
1375 if (!quiet)
1376 fprintf_ln(stderr, _("Cannot save the current "
1377 "staged state"));
1378 goto done;
1379 } else if (ret > 0) {
1380 goto done;
1382 } else {
1383 if (stash_working_tree(info, ps)) {
1384 if (!quiet)
1385 fprintf_ln(stderr, _("Cannot save the current "
1386 "worktree state"));
1387 ret = -1;
1388 goto done;
1392 if (!stash_msg_buf->len)
1393 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1394 else
1395 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1398 * `parents` will be empty after calling `commit_tree()`, so there is
1399 * no need to call `free_commit_list()`
1401 parents = NULL;
1402 if (untracked_commit_option)
1403 commit_list_insert(lookup_commit(the_repository,
1404 &info->u_commit),
1405 &parents);
1406 commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1407 &parents);
1408 commit_list_insert(head_commit, &parents);
1410 if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1411 parents, &info->w_commit, NULL, NULL)) {
1412 if (!quiet)
1413 fprintf_ln(stderr, _("Cannot record "
1414 "working tree state"));
1415 ret = -1;
1416 goto done;
1419 done:
1420 strbuf_release(&commit_tree_label);
1421 strbuf_release(&msg);
1422 strbuf_release(&untracked_files);
1423 return ret;
1426 static int create_stash(int argc, const char **argv, const char *prefix)
1428 int ret = 0;
1429 struct strbuf stash_msg_buf = STRBUF_INIT;
1430 struct stash_info info;
1431 struct pathspec ps;
1433 /* Starting with argv[1], since argv[0] is "create" */
1434 strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
1436 memset(&ps, 0, sizeof(ps));
1437 if (!check_changes_tracked_files(&ps))
1438 return 0;
1440 ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, 0, &info,
1441 NULL, 0);
1442 if (!ret)
1443 printf_ln("%s", oid_to_hex(&info.w_commit));
1445 strbuf_release(&stash_msg_buf);
1446 return ret;
1449 static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int quiet,
1450 int keep_index, int patch_mode, int include_untracked, int only_staged)
1452 int ret = 0;
1453 struct stash_info info;
1454 struct strbuf patch = STRBUF_INIT;
1455 struct strbuf stash_msg_buf = STRBUF_INIT;
1456 struct strbuf untracked_files = STRBUF_INIT;
1458 if (patch_mode && keep_index == -1)
1459 keep_index = 1;
1461 if (patch_mode && include_untracked) {
1462 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1463 " or --all at the same time"));
1464 ret = -1;
1465 goto done;
1468 /* --patch overrides --staged */
1469 if (patch_mode)
1470 only_staged = 0;
1472 if (only_staged && include_untracked) {
1473 fprintf_ln(stderr, _("Can't use --staged and --include-untracked"
1474 " or --all at the same time"));
1475 ret = -1;
1476 goto done;
1479 read_cache_preload(NULL);
1480 if (!include_untracked && ps->nr) {
1481 int i;
1482 char *ps_matched = xcalloc(ps->nr, 1);
1484 /* TODO: audit for interaction with sparse-index. */
1485 ensure_full_index(&the_index);
1486 for (i = 0; i < active_nr; i++)
1487 ce_path_match(&the_index, active_cache[i], ps,
1488 ps_matched);
1490 if (report_path_error(ps_matched, ps)) {
1491 fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1492 ret = -1;
1493 free(ps_matched);
1494 goto done;
1496 free(ps_matched);
1499 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0)) {
1500 ret = -1;
1501 goto done;
1504 if (!check_changes(ps, include_untracked, &untracked_files)) {
1505 if (!quiet)
1506 printf_ln(_("No local changes to save"));
1507 goto done;
1510 if (!reflog_exists(ref_stash) && do_clear_stash()) {
1511 ret = -1;
1512 if (!quiet)
1513 fprintf_ln(stderr, _("Cannot initialize stash"));
1514 goto done;
1517 if (stash_msg)
1518 strbuf_addstr(&stash_msg_buf, stash_msg);
1519 if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode, only_staged,
1520 &info, &patch, quiet)) {
1521 ret = -1;
1522 goto done;
1525 if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1526 ret = -1;
1527 if (!quiet)
1528 fprintf_ln(stderr, _("Cannot save the current status"));
1529 goto done;
1532 if (!quiet)
1533 printf_ln(_("Saved working directory and index state %s"),
1534 stash_msg_buf.buf);
1536 if (!(patch_mode || only_staged)) {
1537 if (include_untracked && !ps->nr) {
1538 struct child_process cp = CHILD_PROCESS_INIT;
1540 cp.git_cmd = 1;
1541 strvec_pushl(&cp.args, "clean", "--force",
1542 "--quiet", "-d", NULL);
1543 if (include_untracked == INCLUDE_ALL_FILES)
1544 strvec_push(&cp.args, "-x");
1545 if (run_command(&cp)) {
1546 ret = -1;
1547 goto done;
1550 discard_cache();
1551 if (ps->nr) {
1552 struct child_process cp_add = CHILD_PROCESS_INIT;
1553 struct child_process cp_diff = CHILD_PROCESS_INIT;
1554 struct child_process cp_apply = CHILD_PROCESS_INIT;
1555 struct strbuf out = STRBUF_INIT;
1557 cp_add.git_cmd = 1;
1558 strvec_push(&cp_add.args, "add");
1559 if (!include_untracked)
1560 strvec_push(&cp_add.args, "-u");
1561 if (include_untracked == INCLUDE_ALL_FILES)
1562 strvec_push(&cp_add.args, "--force");
1563 strvec_push(&cp_add.args, "--");
1564 add_pathspecs(&cp_add.args, ps);
1565 if (run_command(&cp_add)) {
1566 ret = -1;
1567 goto done;
1570 cp_diff.git_cmd = 1;
1571 strvec_pushl(&cp_diff.args, "diff-index", "-p",
1572 "--cached", "--binary", "HEAD", "--",
1573 NULL);
1574 add_pathspecs(&cp_diff.args, ps);
1575 if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1576 ret = -1;
1577 goto done;
1580 cp_apply.git_cmd = 1;
1581 strvec_pushl(&cp_apply.args, "apply", "--index",
1582 "-R", NULL);
1583 if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1584 NULL, 0)) {
1585 ret = -1;
1586 goto done;
1588 } else {
1589 struct child_process cp = CHILD_PROCESS_INIT;
1590 cp.git_cmd = 1;
1591 /* BUG: this nukes untracked files in the way */
1592 strvec_pushl(&cp.args, "reset", "--hard", "-q",
1593 "--no-recurse-submodules", NULL);
1594 if (run_command(&cp)) {
1595 ret = -1;
1596 goto done;
1600 if (keep_index == 1 && !is_null_oid(&info.i_tree)) {
1601 struct child_process cp = CHILD_PROCESS_INIT;
1603 cp.git_cmd = 1;
1604 strvec_pushl(&cp.args, "checkout", "--no-overlay",
1605 oid_to_hex(&info.i_tree), "--", NULL);
1606 if (!ps->nr)
1607 strvec_push(&cp.args, ":/");
1608 else
1609 add_pathspecs(&cp.args, ps);
1610 if (run_command(&cp)) {
1611 ret = -1;
1612 goto done;
1615 goto done;
1616 } else {
1617 struct child_process cp = CHILD_PROCESS_INIT;
1619 cp.git_cmd = 1;
1620 strvec_pushl(&cp.args, "apply", "-R", NULL);
1622 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1623 if (!quiet)
1624 fprintf_ln(stderr, _("Cannot remove "
1625 "worktree changes"));
1626 ret = -1;
1627 goto done;
1630 if (keep_index < 1) {
1631 struct child_process cp = CHILD_PROCESS_INIT;
1633 cp.git_cmd = 1;
1634 strvec_pushl(&cp.args, "reset", "-q", "--", NULL);
1635 add_pathspecs(&cp.args, ps);
1636 if (run_command(&cp)) {
1637 ret = -1;
1638 goto done;
1641 goto done;
1644 done:
1645 strbuf_release(&stash_msg_buf);
1646 return ret;
1649 static int push_stash(int argc, const char **argv, const char *prefix,
1650 int push_assumed)
1652 int force_assume = 0;
1653 int keep_index = -1;
1654 int only_staged = 0;
1655 int patch_mode = 0;
1656 int include_untracked = 0;
1657 int quiet = 0;
1658 int pathspec_file_nul = 0;
1659 const char *stash_msg = NULL;
1660 const char *pathspec_from_file = NULL;
1661 struct pathspec ps;
1662 struct option options[] = {
1663 OPT_BOOL('k', "keep-index", &keep_index,
1664 N_("keep index")),
1665 OPT_BOOL('S', "staged", &only_staged,
1666 N_("stash staged changes only")),
1667 OPT_BOOL('p', "patch", &patch_mode,
1668 N_("stash in patch mode")),
1669 OPT__QUIET(&quiet, N_("quiet mode")),
1670 OPT_BOOL('u', "include-untracked", &include_untracked,
1671 N_("include untracked files in stash")),
1672 OPT_SET_INT('a', "all", &include_untracked,
1673 N_("include ignore files"), 2),
1674 OPT_STRING('m', "message", &stash_msg, N_("message"),
1675 N_("stash message")),
1676 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1677 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1678 OPT_END()
1681 if (argc) {
1682 force_assume = !strcmp(argv[0], "-p");
1683 argc = parse_options(argc, argv, prefix, options,
1684 git_stash_push_usage,
1685 PARSE_OPT_KEEP_DASHDASH);
1688 if (argc) {
1689 if (!strcmp(argv[0], "--")) {
1690 argc--;
1691 argv++;
1692 } else if (push_assumed && !force_assume) {
1693 die("subcommand wasn't specified; 'push' can't be assumed due to unexpected token '%s'",
1694 argv[0]);
1698 parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1699 prefix, argv);
1701 if (pathspec_from_file) {
1702 if (patch_mode)
1703 die(_("--pathspec-from-file is incompatible with --patch"));
1705 if (only_staged)
1706 die(_("--pathspec-from-file is incompatible with --staged"));
1708 if (ps.nr)
1709 die(_("--pathspec-from-file is incompatible with pathspec arguments"));
1711 parse_pathspec_file(&ps, 0,
1712 PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1713 prefix, pathspec_from_file, pathspec_file_nul);
1714 } else if (pathspec_file_nul) {
1715 die(_("--pathspec-file-nul requires --pathspec-from-file"));
1718 return do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
1719 include_untracked, only_staged);
1722 static int save_stash(int argc, const char **argv, const char *prefix)
1724 int keep_index = -1;
1725 int only_staged = 0;
1726 int patch_mode = 0;
1727 int include_untracked = 0;
1728 int quiet = 0;
1729 int ret = 0;
1730 const char *stash_msg = NULL;
1731 struct pathspec ps;
1732 struct strbuf stash_msg_buf = STRBUF_INIT;
1733 struct option options[] = {
1734 OPT_BOOL('k', "keep-index", &keep_index,
1735 N_("keep index")),
1736 OPT_BOOL('S', "staged", &only_staged,
1737 N_("stash staged changes only")),
1738 OPT_BOOL('p', "patch", &patch_mode,
1739 N_("stash in patch mode")),
1740 OPT__QUIET(&quiet, N_("quiet mode")),
1741 OPT_BOOL('u', "include-untracked", &include_untracked,
1742 N_("include untracked files in stash")),
1743 OPT_SET_INT('a', "all", &include_untracked,
1744 N_("include ignore files"), 2),
1745 OPT_STRING('m', "message", &stash_msg, "message",
1746 N_("stash message")),
1747 OPT_END()
1750 argc = parse_options(argc, argv, prefix, options,
1751 git_stash_save_usage,
1752 PARSE_OPT_KEEP_DASHDASH);
1754 if (argc)
1755 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
1757 memset(&ps, 0, sizeof(ps));
1758 ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
1759 patch_mode, include_untracked, only_staged);
1761 strbuf_release(&stash_msg_buf);
1762 return ret;
1765 int cmd_stash(int argc, const char **argv, const char *prefix)
1767 pid_t pid = getpid();
1768 const char *index_file;
1769 struct strvec args = STRVEC_INIT;
1771 struct option options[] = {
1772 OPT_END()
1775 git_config(git_stash_config, NULL);
1777 if (use_legacy_stash ||
1778 !git_env_bool("GIT_TEST_STASH_USE_BUILTIN", -1))
1779 warning(_("the stash.useBuiltin support has been removed!\n"
1780 "See its entry in 'git help config' for details."));
1782 argc = parse_options(argc, argv, prefix, options, git_stash_usage,
1783 PARSE_OPT_KEEP_UNKNOWN | PARSE_OPT_KEEP_DASHDASH);
1785 index_file = get_index_file();
1786 strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
1787 (uintmax_t)pid);
1789 if (!argc)
1790 return !!push_stash(0, NULL, prefix, 0);
1791 else if (!strcmp(argv[0], "apply"))
1792 return !!apply_stash(argc, argv, prefix);
1793 else if (!strcmp(argv[0], "clear"))
1794 return !!clear_stash(argc, argv, prefix);
1795 else if (!strcmp(argv[0], "drop"))
1796 return !!drop_stash(argc, argv, prefix);
1797 else if (!strcmp(argv[0], "pop"))
1798 return !!pop_stash(argc, argv, prefix);
1799 else if (!strcmp(argv[0], "branch"))
1800 return !!branch_stash(argc, argv, prefix);
1801 else if (!strcmp(argv[0], "list"))
1802 return !!list_stash(argc, argv, prefix);
1803 else if (!strcmp(argv[0], "show"))
1804 return !!show_stash(argc, argv, prefix);
1805 else if (!strcmp(argv[0], "store"))
1806 return !!store_stash(argc, argv, prefix);
1807 else if (!strcmp(argv[0], "create"))
1808 return !!create_stash(argc, argv, prefix);
1809 else if (!strcmp(argv[0], "push"))
1810 return !!push_stash(argc, argv, prefix, 0);
1811 else if (!strcmp(argv[0], "save"))
1812 return !!save_stash(argc, argv, prefix);
1813 else if (*argv[0] != '-')
1814 usage_msg_opt(xstrfmt(_("unknown subcommand: %s"), argv[0]),
1815 git_stash_usage, options);
1817 /* Assume 'stash push' */
1818 strvec_push(&args, "push");
1819 strvec_pushv(&args, argv);
1820 return !!push_stash(args.nr, args.v, prefix, 1);