doc txt & -h consistency: make "stash" consistent
[git/debian.git] / builtin / stash.c
blob7cc2b403d51e2780f0fac6fd6861a06ab0484af8
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 "merge-ort-wrappers.h"
11 #include "strvec.h"
12 #include "run-command.h"
13 #include "dir.h"
14 #include "entry.h"
15 #include "rerere.h"
16 #include "revision.h"
17 #include "log-tree.h"
18 #include "diffcore.h"
19 #include "exec-cmd.h"
20 #include "reflog.h"
22 #define INCLUDE_ALL_FILES 2
24 #define BUILTIN_STASH_LIST_USAGE \
25 N_("git stash list [<log-options>]")
26 #define BUILTIN_STASH_SHOW_USAGE \
27 N_("git stash show [-u | --include-untracked | --only-untracked] [<diff-options>] [<stash>]")
28 #define BUILTIN_STASH_DROP_USAGE \
29 N_("git stash drop [-q | --quiet] [<stash>]")
30 #define BUILTIN_STASH_POP_USAGE \
31 N_("git stash pop [--index] [-q | --quiet] [<stash>]")
32 #define BUILTIN_STASH_APPLY_USAGE \
33 N_("git stash apply [--index] [-q | --quiet] [<stash>]")
34 #define BUILTIN_STASH_BRANCH_USAGE \
35 N_("git stash branch <branchname> [<stash>]")
36 #define BUILTIN_STASH_STORE_USAGE \
37 N_("git stash store [(-m | --message) <message>] [-q | --quiet] <commit>")
38 #define BUILTIN_STASH_PUSH_USAGE \
39 N_("git stash [push [-p | --patch] [-S | --staged] [-k | --[no-]keep-index] [-q | --quiet]\n" \
40 " [-u | --include-untracked] [-a | --all] [(-m | --message) <message>]\n" \
41 " [--pathspec-from-file=<file> [--pathspec-file-nul]]\n" \
42 " [--] [<pathspec>...]]")
43 #define BUILTIN_STASH_SAVE_USAGE \
44 N_("git stash save [-p | --patch] [-S | --staged] [-k | --[no-]keep-index] [-q | --quiet]\n" \
45 " [-u | --include-untracked] [-a | --all] [<message>]")
46 #define BUILTIN_STASH_CREATE_USAGE \
47 N_("git stash create [<message>]")
48 #define BUILTIN_STASH_CLEAR_USAGE \
49 "git stash clear"
51 static const char * const git_stash_usage[] = {
52 BUILTIN_STASH_LIST_USAGE,
53 BUILTIN_STASH_SHOW_USAGE,
54 BUILTIN_STASH_DROP_USAGE,
55 BUILTIN_STASH_POP_USAGE,
56 BUILTIN_STASH_APPLY_USAGE,
57 BUILTIN_STASH_BRANCH_USAGE,
58 BUILTIN_STASH_PUSH_USAGE,
59 BUILTIN_STASH_SAVE_USAGE,
60 BUILTIN_STASH_CLEAR_USAGE,
61 BUILTIN_STASH_CREATE_USAGE,
62 BUILTIN_STASH_STORE_USAGE,
63 NULL
66 static const char * const git_stash_list_usage[] = {
67 BUILTIN_STASH_LIST_USAGE,
68 NULL
71 static const char * const git_stash_show_usage[] = {
72 BUILTIN_STASH_SHOW_USAGE,
73 NULL
76 static const char * const git_stash_drop_usage[] = {
77 BUILTIN_STASH_DROP_USAGE,
78 NULL
81 static const char * const git_stash_pop_usage[] = {
82 BUILTIN_STASH_POP_USAGE,
83 NULL
86 static const char * const git_stash_apply_usage[] = {
87 BUILTIN_STASH_APPLY_USAGE,
88 NULL
91 static const char * const git_stash_branch_usage[] = {
92 BUILTIN_STASH_BRANCH_USAGE,
93 NULL
96 static const char * const git_stash_clear_usage[] = {
97 BUILTIN_STASH_CLEAR_USAGE,
98 NULL
101 static const char * const git_stash_store_usage[] = {
102 BUILTIN_STASH_STORE_USAGE,
103 NULL
106 static const char * const git_stash_push_usage[] = {
107 BUILTIN_STASH_PUSH_USAGE,
108 NULL
111 static const char * const git_stash_save_usage[] = {
112 BUILTIN_STASH_SAVE_USAGE,
113 NULL
116 static const char ref_stash[] = "refs/stash";
117 static struct strbuf stash_index_path = STRBUF_INIT;
120 * w_commit is set to the commit containing the working tree
121 * b_commit is set to the base commit
122 * i_commit is set to the commit containing the index tree
123 * u_commit is set to the commit containing the untracked files tree
124 * w_tree is set to the working tree
125 * b_tree is set to the base tree
126 * i_tree is set to the index tree
127 * u_tree is set to the untracked files tree
129 struct stash_info {
130 struct object_id w_commit;
131 struct object_id b_commit;
132 struct object_id i_commit;
133 struct object_id u_commit;
134 struct object_id w_tree;
135 struct object_id b_tree;
136 struct object_id i_tree;
137 struct object_id u_tree;
138 struct strbuf revision;
139 int is_stash_ref;
140 int has_u;
143 #define STASH_INFO_INIT { \
144 .revision = STRBUF_INIT, \
147 static void free_stash_info(struct stash_info *info)
149 strbuf_release(&info->revision);
152 static void assert_stash_like(struct stash_info *info, const char *revision)
154 if (get_oidf(&info->b_commit, "%s^1", revision) ||
155 get_oidf(&info->w_tree, "%s:", revision) ||
156 get_oidf(&info->b_tree, "%s^1:", revision) ||
157 get_oidf(&info->i_tree, "%s^2:", revision))
158 die(_("'%s' is not a stash-like commit"), revision);
161 static int get_stash_info(struct stash_info *info, int argc, const char **argv)
163 int ret;
164 char *end_of_rev;
165 char *expanded_ref;
166 const char *revision;
167 const char *commit = NULL;
168 struct object_id dummy;
169 struct strbuf symbolic = STRBUF_INIT;
171 if (argc > 1) {
172 int i;
173 struct strbuf refs_msg = STRBUF_INIT;
175 for (i = 0; i < argc; i++)
176 strbuf_addf(&refs_msg, " '%s'", argv[i]);
178 fprintf_ln(stderr, _("Too many revisions specified:%s"),
179 refs_msg.buf);
180 strbuf_release(&refs_msg);
182 return -1;
185 if (argc == 1)
186 commit = argv[0];
188 if (!commit) {
189 if (!ref_exists(ref_stash)) {
190 fprintf_ln(stderr, _("No stash entries found."));
191 return -1;
194 strbuf_addf(&info->revision, "%s@{0}", ref_stash);
195 } else if (strspn(commit, "0123456789") == strlen(commit)) {
196 strbuf_addf(&info->revision, "%s@{%s}", ref_stash, commit);
197 } else {
198 strbuf_addstr(&info->revision, commit);
201 revision = info->revision.buf;
203 if (get_oid(revision, &info->w_commit))
204 return error(_("%s is not a valid reference"), revision);
206 assert_stash_like(info, revision);
208 info->has_u = !get_oidf(&info->u_tree, "%s^3:", revision);
210 end_of_rev = strchrnul(revision, '@');
211 strbuf_add(&symbolic, revision, end_of_rev - revision);
213 ret = dwim_ref(symbolic.buf, symbolic.len, &dummy, &expanded_ref, 0);
214 strbuf_release(&symbolic);
215 switch (ret) {
216 case 0: /* Not found, but valid ref */
217 info->is_stash_ref = 0;
218 break;
219 case 1:
220 info->is_stash_ref = !strcmp(expanded_ref, ref_stash);
221 break;
222 default: /* Invalid or ambiguous */
223 break;
226 free(expanded_ref);
227 return !(ret == 0 || ret == 1);
230 static int do_clear_stash(void)
232 struct object_id obj;
233 if (get_oid(ref_stash, &obj))
234 return 0;
236 return delete_ref(NULL, ref_stash, &obj, 0);
239 static int clear_stash(int argc, const char **argv, const char *prefix)
241 struct option options[] = {
242 OPT_END()
245 argc = parse_options(argc, argv, prefix, options,
246 git_stash_clear_usage,
247 PARSE_OPT_STOP_AT_NON_OPTION);
249 if (argc)
250 return error(_("git stash clear with arguments is "
251 "unimplemented"));
253 return do_clear_stash();
256 static int reset_tree(struct object_id *i_tree, int update, int reset)
258 int nr_trees = 1;
259 struct unpack_trees_options opts;
260 struct tree_desc t[MAX_UNPACK_TREES];
261 struct tree *tree;
262 struct lock_file lock_file = LOCK_INIT;
264 read_cache_preload(NULL);
265 if (refresh_cache(REFRESH_QUIET))
266 return -1;
268 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
270 memset(&opts, 0, sizeof(opts));
272 tree = parse_tree_indirect(i_tree);
273 if (parse_tree(tree))
274 return -1;
276 init_tree_desc(t, tree->buffer, tree->size);
278 opts.head_idx = 1;
279 opts.src_index = &the_index;
280 opts.dst_index = &the_index;
281 opts.merge = 1;
282 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
283 opts.update = update;
284 if (update)
285 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
286 opts.fn = oneway_merge;
288 if (unpack_trees(nr_trees, t, &opts))
289 return -1;
291 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
292 return error(_("unable to write new index file"));
294 return 0;
297 static int diff_tree_binary(struct strbuf *out, struct object_id *w_commit)
299 struct child_process cp = CHILD_PROCESS_INIT;
300 const char *w_commit_hex = oid_to_hex(w_commit);
303 * Diff-tree would not be very hard to replace with a native function,
304 * however it should be done together with apply_cached.
306 cp.git_cmd = 1;
307 strvec_pushl(&cp.args, "diff-tree", "--binary", NULL);
308 strvec_pushf(&cp.args, "%s^2^..%s^2", w_commit_hex, w_commit_hex);
310 return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
313 static int apply_cached(struct strbuf *out)
315 struct child_process cp = CHILD_PROCESS_INIT;
318 * Apply currently only reads either from stdin or a file, thus
319 * apply_all_patches would have to be updated to optionally take a
320 * buffer.
322 cp.git_cmd = 1;
323 strvec_pushl(&cp.args, "apply", "--cached", NULL);
324 return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
327 static int reset_head(void)
329 struct child_process cp = CHILD_PROCESS_INIT;
332 * Reset is overall quite simple, however there is no current public
333 * API for resetting.
335 cp.git_cmd = 1;
336 strvec_pushl(&cp.args, "reset", "--quiet", "--refresh", NULL);
338 return run_command(&cp);
341 static int is_path_a_directory(const char *path)
344 * This function differs from abspath.c:is_directory() in that
345 * here we use lstat() instead of stat(); we do not want to
346 * follow symbolic links here.
348 struct stat st;
349 return (!lstat(path, &st) && S_ISDIR(st.st_mode));
352 static void add_diff_to_buf(struct diff_queue_struct *q,
353 struct diff_options *options,
354 void *data)
356 int i;
358 for (i = 0; i < q->nr; i++) {
359 if (is_path_a_directory(q->queue[i]->one->path))
360 continue;
362 strbuf_addstr(data, q->queue[i]->one->path);
364 /* NUL-terminate: will be fed to update-index -z */
365 strbuf_addch(data, '\0');
369 static int restore_untracked(struct object_id *u_tree)
371 int res;
372 struct child_process cp = CHILD_PROCESS_INIT;
375 * We need to run restore files from a given index, but without
376 * affecting the current index, so we use GIT_INDEX_FILE with
377 * run_command to fork processes that will not interfere.
379 cp.git_cmd = 1;
380 strvec_push(&cp.args, "read-tree");
381 strvec_push(&cp.args, oid_to_hex(u_tree));
382 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
383 stash_index_path.buf);
384 if (run_command(&cp)) {
385 remove_path(stash_index_path.buf);
386 return -1;
389 child_process_init(&cp);
390 cp.git_cmd = 1;
391 strvec_pushl(&cp.args, "checkout-index", "--all", NULL);
392 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
393 stash_index_path.buf);
395 res = run_command(&cp);
396 remove_path(stash_index_path.buf);
397 return res;
400 static void unstage_changes_unless_new(struct object_id *orig_tree)
403 * When we enter this function, there has been a clean merge of
404 * relevant trees, and the merge logic always stages whatever merges
405 * cleanly. We want to unstage those changes, unless it corresponds
406 * to a file that didn't exist as of orig_tree.
408 * However, if any SKIP_WORKTREE path is modified relative to
409 * orig_tree, then we want to clear the SKIP_WORKTREE bit and write
410 * it to the worktree before unstaging.
413 struct checkout state = CHECKOUT_INIT;
414 struct diff_options diff_opts;
415 struct lock_file lock = LOCK_INIT;
416 int i;
418 /* If any entries have skip_worktree set, we'll have to check 'em out */
419 state.force = 1;
420 state.quiet = 1;
421 state.refresh_cache = 1;
422 state.istate = &the_index;
425 * Step 1: get a difference between orig_tree (which corresponding
426 * to the index before a merge was run) and the current index
427 * (reflecting the changes brought in by the merge).
429 diff_setup(&diff_opts);
430 diff_opts.flags.recursive = 1;
431 diff_opts.detect_rename = 0;
432 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
433 diff_setup_done(&diff_opts);
435 do_diff_cache(orig_tree, &diff_opts);
436 diffcore_std(&diff_opts);
438 /* Iterate over the paths that changed due to the merge... */
439 for (i = 0; i < diff_queued_diff.nr; i++) {
440 struct diff_filepair *p;
441 struct cache_entry *ce;
442 int pos;
444 /* Look up the path's position in the current index. */
445 p = diff_queued_diff.queue[i];
446 pos = index_name_pos(&the_index, p->two->path,
447 strlen(p->two->path));
450 * Step 2: Place changes in the working tree
452 * Stash is about restoring changes *to the working tree*.
453 * So if the merge successfully got a new version of some
454 * path, but left it out of the working tree, then clear the
455 * SKIP_WORKTREE bit and write it to the working tree.
457 if (pos >= 0 && ce_skip_worktree(active_cache[pos])) {
458 struct stat st;
460 ce = active_cache[pos];
461 if (!lstat(ce->name, &st)) {
462 /* Conflicting path present; relocate it */
463 struct strbuf new_path = STRBUF_INIT;
464 int fd;
466 strbuf_addf(&new_path,
467 "%s.stash.XXXXXX", ce->name);
468 fd = xmkstemp(new_path.buf);
469 close(fd);
470 printf(_("WARNING: Untracked file in way of "
471 "tracked file! Renaming\n "
472 " %s -> %s\n"
473 " to make room.\n"),
474 ce->name, new_path.buf);
475 if (rename(ce->name, new_path.buf))
476 die("Failed to move %s to %s\n",
477 ce->name, new_path.buf);
478 strbuf_release(&new_path);
480 checkout_entry(ce, &state, NULL, NULL);
481 ce->ce_flags &= ~CE_SKIP_WORKTREE;
485 * Step 3: "unstage" changes, as long as they are still tracked
487 if (p->one->oid_valid) {
489 * Path existed in orig_tree; restore index entry
490 * from that tree in order to "unstage" the changes.
492 int option = ADD_CACHE_OK_TO_REPLACE;
493 if (pos < 0)
494 option = ADD_CACHE_OK_TO_ADD;
496 ce = make_cache_entry(&the_index,
497 p->one->mode,
498 &p->one->oid,
499 p->one->path,
500 0, 0);
501 add_index_entry(&the_index, ce, option);
504 diff_flush(&diff_opts);
507 * Step 4: write the new index to disk
509 repo_hold_locked_index(the_repository, &lock, LOCK_DIE_ON_ERROR);
510 if (write_locked_index(&the_index, &lock,
511 COMMIT_LOCK | SKIP_IF_UNCHANGED))
512 die(_("Unable to write index."));
515 static int do_apply_stash(const char *prefix, struct stash_info *info,
516 int index, int quiet)
518 int clean, ret;
519 int has_index = index;
520 struct merge_options o;
521 struct object_id c_tree;
522 struct object_id index_tree;
523 struct tree *head, *merge, *merge_base;
524 struct lock_file lock = LOCK_INIT;
526 read_cache_preload(NULL);
527 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0))
528 return -1;
530 if (write_cache_as_tree(&c_tree, 0, NULL))
531 return error(_("cannot apply a stash in the middle of a merge"));
533 if (index) {
534 if (oideq(&info->b_tree, &info->i_tree) ||
535 oideq(&c_tree, &info->i_tree)) {
536 has_index = 0;
537 } else {
538 struct strbuf out = STRBUF_INIT;
540 if (diff_tree_binary(&out, &info->w_commit)) {
541 strbuf_release(&out);
542 return error(_("could not generate diff %s^!."),
543 oid_to_hex(&info->w_commit));
546 ret = apply_cached(&out);
547 strbuf_release(&out);
548 if (ret)
549 return error(_("conflicts in index. "
550 "Try without --index."));
552 discard_cache();
553 read_cache();
554 if (write_cache_as_tree(&index_tree, 0, NULL))
555 return error(_("could not save index tree"));
557 reset_head();
558 discard_cache();
559 read_cache();
563 init_merge_options(&o, the_repository);
565 o.branch1 = "Updated upstream";
566 o.branch2 = "Stashed changes";
567 o.ancestor = "Stash base";
569 if (oideq(&info->b_tree, &c_tree))
570 o.branch1 = "Version stash was based on";
572 if (quiet)
573 o.verbosity = 0;
575 if (o.verbosity >= 3)
576 printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
578 head = lookup_tree(o.repo, &c_tree);
579 merge = lookup_tree(o.repo, &info->w_tree);
580 merge_base = lookup_tree(o.repo, &info->b_tree);
582 repo_hold_locked_index(o.repo, &lock, LOCK_DIE_ON_ERROR);
583 clean = merge_ort_nonrecursive(&o, head, merge, merge_base);
586 * If 'clean' >= 0, reverse the value for 'ret' so 'ret' is 0 when the
587 * merge was clean, and nonzero if the merge was unclean or encountered
588 * an error.
590 ret = clean >= 0 ? !clean : clean;
592 if (ret < 0)
593 rollback_lock_file(&lock);
594 else if (write_locked_index(o.repo->index, &lock,
595 COMMIT_LOCK | SKIP_IF_UNCHANGED))
596 ret = error(_("could not write index"));
598 if (ret) {
599 rerere(0);
601 if (index)
602 fprintf_ln(stderr, _("Index was not unstashed."));
604 goto restore_untracked;
607 if (has_index) {
608 if (reset_tree(&index_tree, 0, 0))
609 ret = -1;
610 } else {
611 unstage_changes_unless_new(&c_tree);
614 restore_untracked:
615 if (info->has_u && restore_untracked(&info->u_tree))
616 ret = error(_("could not restore untracked files from stash"));
618 if (!quiet) {
619 struct child_process cp = CHILD_PROCESS_INIT;
622 * Status is quite simple and could be replaced with calls to
623 * wt_status in the future, but it adds complexities which may
624 * require more tests.
626 cp.git_cmd = 1;
627 cp.dir = prefix;
628 strvec_pushf(&cp.env, GIT_WORK_TREE_ENVIRONMENT"=%s",
629 absolute_path(get_git_work_tree()));
630 strvec_pushf(&cp.env, GIT_DIR_ENVIRONMENT"=%s",
631 absolute_path(get_git_dir()));
632 strvec_push(&cp.args, "status");
633 run_command(&cp);
636 return ret;
639 static int apply_stash(int argc, const char **argv, const char *prefix)
641 int ret = -1;
642 int quiet = 0;
643 int index = 0;
644 struct stash_info info = STASH_INFO_INIT;
645 struct option options[] = {
646 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
647 OPT_BOOL(0, "index", &index,
648 N_("attempt to recreate the index")),
649 OPT_END()
652 argc = parse_options(argc, argv, prefix, options,
653 git_stash_apply_usage, 0);
655 if (get_stash_info(&info, argc, argv))
656 goto cleanup;
658 ret = do_apply_stash(prefix, &info, index, quiet);
659 cleanup:
660 free_stash_info(&info);
661 return ret;
664 static int reject_reflog_ent(struct object_id *ooid, struct object_id *noid,
665 const char *email, timestamp_t timestamp, int tz,
666 const char *message, void *cb_data)
668 return 1;
671 static int reflog_is_empty(const char *refname)
673 return !for_each_reflog_ent(refname, reject_reflog_ent, NULL);
676 static int do_drop_stash(struct stash_info *info, int quiet)
678 if (!reflog_delete(info->revision.buf,
679 EXPIRE_REFLOGS_REWRITE | EXPIRE_REFLOGS_UPDATE_REF,
680 0)) {
681 if (!quiet)
682 printf_ln(_("Dropped %s (%s)"), info->revision.buf,
683 oid_to_hex(&info->w_commit));
684 } else {
685 return error(_("%s: Could not drop stash entry"),
686 info->revision.buf);
689 if (reflog_is_empty(ref_stash))
690 do_clear_stash();
692 return 0;
695 static int get_stash_info_assert(struct stash_info *info, int argc,
696 const char **argv)
698 int ret = get_stash_info(info, argc, argv);
700 if (ret < 0)
701 return ret;
703 if (!info->is_stash_ref)
704 return error(_("'%s' is not a stash reference"), info->revision.buf);
706 return 0;
709 static int drop_stash(int argc, const char **argv, const char *prefix)
711 int ret = -1;
712 int quiet = 0;
713 struct stash_info info = STASH_INFO_INIT;
714 struct option options[] = {
715 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
716 OPT_END()
719 argc = parse_options(argc, argv, prefix, options,
720 git_stash_drop_usage, 0);
722 if (get_stash_info_assert(&info, argc, argv))
723 goto cleanup;
725 ret = do_drop_stash(&info, quiet);
726 cleanup:
727 free_stash_info(&info);
728 return ret;
731 static int pop_stash(int argc, const char **argv, const char *prefix)
733 int ret = -1;
734 int index = 0;
735 int quiet = 0;
736 struct stash_info info = STASH_INFO_INIT;
737 struct option options[] = {
738 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
739 OPT_BOOL(0, "index", &index,
740 N_("attempt to recreate the index")),
741 OPT_END()
744 argc = parse_options(argc, argv, prefix, options,
745 git_stash_pop_usage, 0);
747 if (get_stash_info_assert(&info, argc, argv))
748 goto cleanup;
750 if ((ret = do_apply_stash(prefix, &info, index, quiet)))
751 printf_ln(_("The stash entry is kept in case "
752 "you need it again."));
753 else
754 ret = do_drop_stash(&info, quiet);
756 cleanup:
757 free_stash_info(&info);
758 return ret;
761 static int branch_stash(int argc, const char **argv, const char *prefix)
763 int ret = -1;
764 const char *branch = NULL;
765 struct stash_info info = STASH_INFO_INIT;
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_branch_usage, 0);
774 if (!argc) {
775 fprintf_ln(stderr, _("No branch name specified"));
776 return -1;
779 branch = argv[0];
781 if (get_stash_info(&info, argc - 1, argv + 1))
782 goto cleanup;
784 cp.git_cmd = 1;
785 strvec_pushl(&cp.args, "checkout", "-b", NULL);
786 strvec_push(&cp.args, branch);
787 strvec_push(&cp.args, oid_to_hex(&info.b_commit));
788 ret = run_command(&cp);
789 if (!ret)
790 ret = do_apply_stash(prefix, &info, 1, 0);
791 if (!ret && info.is_stash_ref)
792 ret = do_drop_stash(&info, 0);
794 cleanup:
795 free_stash_info(&info);
796 return ret;
799 static int list_stash(int argc, const char **argv, const char *prefix)
801 struct child_process cp = CHILD_PROCESS_INIT;
802 struct option options[] = {
803 OPT_END()
806 argc = parse_options(argc, argv, prefix, options,
807 git_stash_list_usage,
808 PARSE_OPT_KEEP_UNKNOWN_OPT);
810 if (!ref_exists(ref_stash))
811 return 0;
813 cp.git_cmd = 1;
814 strvec_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
815 "--first-parent", NULL);
816 strvec_pushv(&cp.args, argv);
817 strvec_push(&cp.args, ref_stash);
818 strvec_push(&cp.args, "--");
819 return run_command(&cp);
822 static int show_stat = 1;
823 static int show_patch;
824 static int show_include_untracked;
826 static int git_stash_config(const char *var, const char *value, void *cb)
828 if (!strcmp(var, "stash.showstat")) {
829 show_stat = git_config_bool(var, value);
830 return 0;
832 if (!strcmp(var, "stash.showpatch")) {
833 show_patch = git_config_bool(var, value);
834 return 0;
836 if (!strcmp(var, "stash.showincludeuntracked")) {
837 show_include_untracked = git_config_bool(var, value);
838 return 0;
840 return git_diff_basic_config(var, value, cb);
843 static void diff_include_untracked(const struct stash_info *info, struct diff_options *diff_opt)
845 const struct object_id *oid[] = { &info->w_commit, &info->u_tree };
846 struct tree *tree[ARRAY_SIZE(oid)];
847 struct tree_desc tree_desc[ARRAY_SIZE(oid)];
848 struct unpack_trees_options unpack_tree_opt = { 0 };
849 int i;
851 for (i = 0; i < ARRAY_SIZE(oid); i++) {
852 tree[i] = parse_tree_indirect(oid[i]);
853 if (parse_tree(tree[i]) < 0)
854 die(_("failed to parse tree"));
855 init_tree_desc(&tree_desc[i], tree[i]->buffer, tree[i]->size);
858 unpack_tree_opt.head_idx = -1;
859 unpack_tree_opt.src_index = &the_index;
860 unpack_tree_opt.dst_index = &the_index;
861 unpack_tree_opt.merge = 1;
862 unpack_tree_opt.fn = stash_worktree_untracked_merge;
864 if (unpack_trees(ARRAY_SIZE(tree_desc), tree_desc, &unpack_tree_opt))
865 die(_("failed to unpack trees"));
867 do_diff_cache(&info->b_commit, diff_opt);
870 static int show_stash(int argc, const char **argv, const char *prefix)
872 int i;
873 int ret = -1;
874 struct stash_info info = STASH_INFO_INIT;
875 struct rev_info rev;
876 struct strvec stash_args = STRVEC_INIT;
877 struct strvec revision_args = STRVEC_INIT;
878 enum {
879 UNTRACKED_NONE,
880 UNTRACKED_INCLUDE,
881 UNTRACKED_ONLY
882 } show_untracked = show_include_untracked ? UNTRACKED_INCLUDE : UNTRACKED_NONE;
883 struct option options[] = {
884 OPT_SET_INT('u', "include-untracked", &show_untracked,
885 N_("include untracked files in the stash"),
886 UNTRACKED_INCLUDE),
887 OPT_SET_INT_F(0, "only-untracked", &show_untracked,
888 N_("only show untracked files in the stash"),
889 UNTRACKED_ONLY, PARSE_OPT_NONEG),
890 OPT_END()
892 int do_usage = 0;
894 init_diff_ui_defaults();
895 git_config(git_diff_ui_config, NULL);
896 init_revisions(&rev, prefix);
898 argc = parse_options(argc, argv, prefix, options, git_stash_show_usage,
899 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
900 PARSE_OPT_KEEP_DASHDASH);
902 strvec_push(&revision_args, argv[0]);
903 for (i = 1; i < argc; i++) {
904 if (argv[i][0] != '-')
905 strvec_push(&stash_args, argv[i]);
906 else
907 strvec_push(&revision_args, argv[i]);
910 if (get_stash_info(&info, stash_args.nr, stash_args.v))
911 goto cleanup;
914 * The config settings are applied only if there are not passed
915 * any options.
917 if (revision_args.nr == 1) {
918 if (show_stat)
919 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
921 if (show_patch)
922 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
924 if (!show_stat && !show_patch) {
925 ret = 0;
926 goto cleanup;
930 argc = setup_revisions(revision_args.nr, revision_args.v, &rev, NULL);
931 if (argc > 1)
932 goto usage;
933 if (!rev.diffopt.output_format) {
934 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
935 diff_setup_done(&rev.diffopt);
938 rev.diffopt.flags.recursive = 1;
939 setup_diff_pager(&rev.diffopt);
940 switch (show_untracked) {
941 case UNTRACKED_NONE:
942 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
943 break;
944 case UNTRACKED_ONLY:
945 if (info.has_u)
946 diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
947 break;
948 case UNTRACKED_INCLUDE:
949 if (info.has_u)
950 diff_include_untracked(&info, &rev.diffopt);
951 else
952 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
953 break;
955 log_tree_diff_flush(&rev);
957 ret = diff_result_code(&rev.diffopt, 0);
958 cleanup:
959 strvec_clear(&stash_args);
960 free_stash_info(&info);
961 release_revisions(&rev);
962 if (do_usage)
963 usage_with_options(git_stash_show_usage, options);
964 return ret;
965 usage:
966 do_usage = 1;
967 goto cleanup;
970 static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
971 int quiet)
973 if (!stash_msg)
974 stash_msg = "Created via \"git stash store\".";
976 if (update_ref(stash_msg, ref_stash, w_commit, NULL,
977 REF_FORCE_CREATE_REFLOG,
978 quiet ? UPDATE_REFS_QUIET_ON_ERR :
979 UPDATE_REFS_MSG_ON_ERR)) {
980 if (!quiet) {
981 fprintf_ln(stderr, _("Cannot update %s with %s"),
982 ref_stash, oid_to_hex(w_commit));
984 return -1;
987 return 0;
990 static int store_stash(int argc, const char **argv, const char *prefix)
992 int quiet = 0;
993 const char *stash_msg = NULL;
994 struct object_id obj;
995 struct object_context dummy;
996 struct option options[] = {
997 OPT__QUIET(&quiet, N_("be quiet")),
998 OPT_STRING('m', "message", &stash_msg, "message",
999 N_("stash message")),
1000 OPT_END()
1003 argc = parse_options(argc, argv, prefix, options,
1004 git_stash_store_usage,
1005 PARSE_OPT_KEEP_UNKNOWN_OPT);
1007 if (argc != 1) {
1008 if (!quiet)
1009 fprintf_ln(stderr, _("\"git stash store\" requires one "
1010 "<commit> argument"));
1011 return -1;
1014 if (get_oid_with_context(the_repository,
1015 argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
1016 &dummy)) {
1017 if (!quiet)
1018 fprintf_ln(stderr, _("Cannot update %s with %s"),
1019 ref_stash, argv[0]);
1020 return -1;
1023 return do_store_stash(&obj, stash_msg, quiet);
1026 static void add_pathspecs(struct strvec *args,
1027 const struct pathspec *ps) {
1028 int i;
1030 for (i = 0; i < ps->nr; i++)
1031 strvec_push(args, ps->items[i].original);
1035 * `untracked_files` will be filled with the names of untracked files.
1036 * The return value is:
1038 * = 0 if there are not any untracked files
1039 * > 0 if there are untracked files
1041 static int get_untracked_files(const struct pathspec *ps, int include_untracked,
1042 struct strbuf *untracked_files)
1044 int i;
1045 int found = 0;
1046 struct dir_struct dir = DIR_INIT;
1048 if (include_untracked != INCLUDE_ALL_FILES)
1049 setup_standard_excludes(&dir);
1051 fill_directory(&dir, the_repository->index, ps);
1052 for (i = 0; i < dir.nr; i++) {
1053 struct dir_entry *ent = dir.entries[i];
1054 found++;
1055 strbuf_addstr(untracked_files, ent->name);
1056 /* NUL-terminate: will be fed to update-index -z */
1057 strbuf_addch(untracked_files, '\0');
1060 dir_clear(&dir);
1061 return found;
1065 * The return value of `check_changes_tracked_files()` can be:
1067 * < 0 if there was an error
1068 * = 0 if there are no changes.
1069 * > 0 if there are changes.
1071 static int check_changes_tracked_files(const struct pathspec *ps)
1073 int result;
1074 struct rev_info rev;
1075 struct object_id dummy;
1076 int ret = 0;
1078 /* No initial commit. */
1079 if (get_oid("HEAD", &dummy))
1080 return -1;
1082 if (read_cache() < 0)
1083 return -1;
1085 init_revisions(&rev, NULL);
1086 copy_pathspec(&rev.prune_data, ps);
1088 rev.diffopt.flags.quick = 1;
1089 rev.diffopt.flags.ignore_submodules = 1;
1090 rev.abbrev = 0;
1092 add_head_to_pending(&rev);
1093 diff_setup_done(&rev.diffopt);
1095 result = run_diff_index(&rev, 1);
1096 if (diff_result_code(&rev.diffopt, result)) {
1097 ret = 1;
1098 goto done;
1101 result = run_diff_files(&rev, 0);
1102 if (diff_result_code(&rev.diffopt, result)) {
1103 ret = 1;
1104 goto done;
1107 done:
1108 release_revisions(&rev);
1109 return ret;
1113 * The function will fill `untracked_files` with the names of untracked files
1114 * It will return 1 if there were any changes and 0 if there were not.
1116 static int check_changes(const struct pathspec *ps, int include_untracked,
1117 struct strbuf *untracked_files)
1119 int ret = 0;
1120 if (check_changes_tracked_files(ps))
1121 ret = 1;
1123 if (include_untracked && get_untracked_files(ps, include_untracked,
1124 untracked_files))
1125 ret = 1;
1127 return ret;
1130 static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
1131 struct strbuf files)
1133 int ret = 0;
1134 struct strbuf untracked_msg = STRBUF_INIT;
1135 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1136 struct index_state istate = { NULL };
1138 cp_upd_index.git_cmd = 1;
1139 strvec_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
1140 "--remove", "--stdin", NULL);
1141 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1142 stash_index_path.buf);
1144 strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
1145 if (pipe_command(&cp_upd_index, files.buf, files.len, NULL, 0,
1146 NULL, 0)) {
1147 ret = -1;
1148 goto done;
1151 if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
1152 NULL)) {
1153 ret = -1;
1154 goto done;
1157 if (commit_tree(untracked_msg.buf, untracked_msg.len,
1158 &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
1159 ret = -1;
1160 goto done;
1163 done:
1164 discard_index(&istate);
1165 strbuf_release(&untracked_msg);
1166 remove_path(stash_index_path.buf);
1167 return ret;
1170 static int stash_staged(struct stash_info *info, struct strbuf *out_patch,
1171 int quiet)
1173 int ret = 0;
1174 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1175 struct index_state istate = { NULL };
1177 if (write_index_as_tree(&info->w_tree, &istate, the_repository->index_file,
1178 0, NULL)) {
1179 ret = -1;
1180 goto done;
1183 cp_diff_tree.git_cmd = 1;
1184 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1185 oid_to_hex(&info->w_tree), "--", NULL);
1186 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1187 ret = -1;
1188 goto done;
1191 if (!out_patch->len) {
1192 if (!quiet)
1193 fprintf_ln(stderr, _("No staged changes"));
1194 ret = 1;
1197 done:
1198 discard_index(&istate);
1199 return ret;
1202 static int stash_patch(struct stash_info *info, const struct pathspec *ps,
1203 struct strbuf *out_patch, int quiet)
1205 int ret = 0;
1206 struct child_process cp_read_tree = CHILD_PROCESS_INIT;
1207 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1208 struct index_state istate = { NULL };
1209 char *old_index_env = NULL, *old_repo_index_file;
1211 remove_path(stash_index_path.buf);
1213 cp_read_tree.git_cmd = 1;
1214 strvec_pushl(&cp_read_tree.args, "read-tree", "HEAD", NULL);
1215 strvec_pushf(&cp_read_tree.env, "GIT_INDEX_FILE=%s",
1216 stash_index_path.buf);
1217 if (run_command(&cp_read_tree)) {
1218 ret = -1;
1219 goto done;
1222 /* Find out what the user wants. */
1223 old_repo_index_file = the_repository->index_file;
1224 the_repository->index_file = stash_index_path.buf;
1225 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
1226 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
1228 ret = run_add_interactive(NULL, "--patch=stash", ps);
1230 the_repository->index_file = old_repo_index_file;
1231 if (old_index_env && *old_index_env)
1232 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
1233 else
1234 unsetenv(INDEX_ENVIRONMENT);
1235 FREE_AND_NULL(old_index_env);
1237 /* State of the working tree. */
1238 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1239 NULL)) {
1240 ret = -1;
1241 goto done;
1244 cp_diff_tree.git_cmd = 1;
1245 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1246 oid_to_hex(&info->w_tree), "--", NULL);
1247 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1248 ret = -1;
1249 goto done;
1252 if (!out_patch->len) {
1253 if (!quiet)
1254 fprintf_ln(stderr, _("No changes selected"));
1255 ret = 1;
1258 done:
1259 discard_index(&istate);
1260 remove_path(stash_index_path.buf);
1261 return ret;
1264 static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
1266 int ret = 0;
1267 struct rev_info rev;
1268 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1269 struct strbuf diff_output = STRBUF_INIT;
1270 struct index_state istate = { NULL };
1272 init_revisions(&rev, NULL);
1273 copy_pathspec(&rev.prune_data, ps);
1275 set_alternate_index_output(stash_index_path.buf);
1276 if (reset_tree(&info->i_tree, 0, 0)) {
1277 ret = -1;
1278 goto done;
1280 set_alternate_index_output(NULL);
1282 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1283 rev.diffopt.format_callback = add_diff_to_buf;
1284 rev.diffopt.format_callback_data = &diff_output;
1286 if (read_cache_preload(&rev.diffopt.pathspec) < 0) {
1287 ret = -1;
1288 goto done;
1291 add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1292 "");
1293 if (run_diff_index(&rev, 0)) {
1294 ret = -1;
1295 goto done;
1298 cp_upd_index.git_cmd = 1;
1299 strvec_pushl(&cp_upd_index.args, "update-index",
1300 "--ignore-skip-worktree-entries",
1301 "-z", "--add", "--remove", "--stdin", NULL);
1302 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1303 stash_index_path.buf);
1305 if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1306 NULL, 0, NULL, 0)) {
1307 ret = -1;
1308 goto done;
1311 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1312 NULL)) {
1313 ret = -1;
1314 goto done;
1317 done:
1318 discard_index(&istate);
1319 release_revisions(&rev);
1320 strbuf_release(&diff_output);
1321 remove_path(stash_index_path.buf);
1322 return ret;
1325 static int do_create_stash(const struct pathspec *ps, struct strbuf *stash_msg_buf,
1326 int include_untracked, int patch_mode, int only_staged,
1327 struct stash_info *info, struct strbuf *patch,
1328 int quiet)
1330 int ret = 0;
1331 int flags = 0;
1332 int untracked_commit_option = 0;
1333 const char *head_short_sha1 = NULL;
1334 const char *branch_ref = NULL;
1335 const char *branch_name = "(no branch)";
1336 struct commit *head_commit = NULL;
1337 struct commit_list *parents = NULL;
1338 struct strbuf msg = STRBUF_INIT;
1339 struct strbuf commit_tree_label = STRBUF_INIT;
1340 struct strbuf untracked_files = STRBUF_INIT;
1342 prepare_fallback_ident("git stash", "git@stash");
1344 read_cache_preload(NULL);
1345 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0) < 0) {
1346 ret = -1;
1347 goto done;
1350 if (get_oid("HEAD", &info->b_commit)) {
1351 if (!quiet)
1352 fprintf_ln(stderr, _("You do not have "
1353 "the initial commit yet"));
1354 ret = -1;
1355 goto done;
1356 } else {
1357 head_commit = lookup_commit(the_repository, &info->b_commit);
1360 if (!check_changes(ps, include_untracked, &untracked_files)) {
1361 ret = 1;
1362 goto done;
1365 branch_ref = resolve_ref_unsafe("HEAD", 0, NULL, &flags);
1366 if (flags & REF_ISSYMREF)
1367 skip_prefix(branch_ref, "refs/heads/", &branch_name);
1368 head_short_sha1 = find_unique_abbrev(&head_commit->object.oid,
1369 DEFAULT_ABBREV);
1370 strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1371 pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1373 strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1374 commit_list_insert(head_commit, &parents);
1375 if (write_cache_as_tree(&info->i_tree, 0, NULL) ||
1376 commit_tree(commit_tree_label.buf, commit_tree_label.len,
1377 &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1378 if (!quiet)
1379 fprintf_ln(stderr, _("Cannot save the current "
1380 "index state"));
1381 ret = -1;
1382 goto done;
1385 if (include_untracked) {
1386 if (save_untracked_files(info, &msg, untracked_files)) {
1387 if (!quiet)
1388 fprintf_ln(stderr, _("Cannot save "
1389 "the untracked files"));
1390 ret = -1;
1391 goto done;
1393 untracked_commit_option = 1;
1395 if (patch_mode) {
1396 ret = stash_patch(info, ps, patch, quiet);
1397 if (ret < 0) {
1398 if (!quiet)
1399 fprintf_ln(stderr, _("Cannot save the current "
1400 "worktree state"));
1401 goto done;
1402 } else if (ret > 0) {
1403 goto done;
1405 } else if (only_staged) {
1406 ret = stash_staged(info, patch, quiet);
1407 if (ret < 0) {
1408 if (!quiet)
1409 fprintf_ln(stderr, _("Cannot save the current "
1410 "staged state"));
1411 goto done;
1412 } else if (ret > 0) {
1413 goto done;
1415 } else {
1416 if (stash_working_tree(info, ps)) {
1417 if (!quiet)
1418 fprintf_ln(stderr, _("Cannot save the current "
1419 "worktree state"));
1420 ret = -1;
1421 goto done;
1425 if (!stash_msg_buf->len)
1426 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1427 else
1428 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1431 * `parents` will be empty after calling `commit_tree()`, so there is
1432 * no need to call `free_commit_list()`
1434 parents = NULL;
1435 if (untracked_commit_option)
1436 commit_list_insert(lookup_commit(the_repository,
1437 &info->u_commit),
1438 &parents);
1439 commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1440 &parents);
1441 commit_list_insert(head_commit, &parents);
1443 if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1444 parents, &info->w_commit, NULL, NULL)) {
1445 if (!quiet)
1446 fprintf_ln(stderr, _("Cannot record "
1447 "working tree state"));
1448 ret = -1;
1449 goto done;
1452 done:
1453 strbuf_release(&commit_tree_label);
1454 strbuf_release(&msg);
1455 strbuf_release(&untracked_files);
1456 return ret;
1459 static int create_stash(int argc, const char **argv, const char *prefix)
1461 int ret;
1462 struct strbuf stash_msg_buf = STRBUF_INIT;
1463 struct stash_info info = STASH_INFO_INIT;
1464 struct pathspec ps;
1466 /* Starting with argv[1], since argv[0] is "create" */
1467 strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
1469 memset(&ps, 0, sizeof(ps));
1470 if (!check_changes_tracked_files(&ps))
1471 return 0;
1473 ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, 0, &info,
1474 NULL, 0);
1475 if (!ret)
1476 printf_ln("%s", oid_to_hex(&info.w_commit));
1478 free_stash_info(&info);
1479 strbuf_release(&stash_msg_buf);
1480 return ret;
1483 static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int quiet,
1484 int keep_index, int patch_mode, int include_untracked, int only_staged)
1486 int ret = 0;
1487 struct stash_info info = STASH_INFO_INIT;
1488 struct strbuf patch = STRBUF_INIT;
1489 struct strbuf stash_msg_buf = STRBUF_INIT;
1490 struct strbuf untracked_files = STRBUF_INIT;
1492 if (patch_mode && keep_index == -1)
1493 keep_index = 1;
1495 if (patch_mode && include_untracked) {
1496 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1497 " or --all at the same time"));
1498 ret = -1;
1499 goto done;
1502 /* --patch overrides --staged */
1503 if (patch_mode)
1504 only_staged = 0;
1506 if (only_staged && include_untracked) {
1507 fprintf_ln(stderr, _("Can't use --staged and --include-untracked"
1508 " or --all at the same time"));
1509 ret = -1;
1510 goto done;
1513 read_cache_preload(NULL);
1514 if (!include_untracked && ps->nr) {
1515 int i;
1516 char *ps_matched = xcalloc(ps->nr, 1);
1518 /* TODO: audit for interaction with sparse-index. */
1519 ensure_full_index(&the_index);
1520 for (i = 0; i < active_nr; i++)
1521 ce_path_match(&the_index, active_cache[i], ps,
1522 ps_matched);
1524 if (report_path_error(ps_matched, ps)) {
1525 fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1526 ret = -1;
1527 free(ps_matched);
1528 goto done;
1530 free(ps_matched);
1533 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0)) {
1534 ret = -1;
1535 goto done;
1538 if (!check_changes(ps, include_untracked, &untracked_files)) {
1539 if (!quiet)
1540 printf_ln(_("No local changes to save"));
1541 goto done;
1544 if (!reflog_exists(ref_stash) && do_clear_stash()) {
1545 ret = -1;
1546 if (!quiet)
1547 fprintf_ln(stderr, _("Cannot initialize stash"));
1548 goto done;
1551 if (stash_msg)
1552 strbuf_addstr(&stash_msg_buf, stash_msg);
1553 if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode, only_staged,
1554 &info, &patch, quiet)) {
1555 ret = -1;
1556 goto done;
1559 if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1560 ret = -1;
1561 if (!quiet)
1562 fprintf_ln(stderr, _("Cannot save the current status"));
1563 goto done;
1566 if (!quiet)
1567 printf_ln(_("Saved working directory and index state %s"),
1568 stash_msg_buf.buf);
1570 if (!(patch_mode || only_staged)) {
1571 if (include_untracked && !ps->nr) {
1572 struct child_process cp = CHILD_PROCESS_INIT;
1574 cp.git_cmd = 1;
1575 if (startup_info->original_cwd) {
1576 cp.dir = startup_info->original_cwd;
1577 strvec_pushf(&cp.env, "%s=%s",
1578 GIT_WORK_TREE_ENVIRONMENT,
1579 the_repository->worktree);
1581 strvec_pushl(&cp.args, "clean", "--force",
1582 "--quiet", "-d", ":/", NULL);
1583 if (include_untracked == INCLUDE_ALL_FILES)
1584 strvec_push(&cp.args, "-x");
1585 if (run_command(&cp)) {
1586 ret = -1;
1587 goto done;
1590 discard_cache();
1591 if (ps->nr) {
1592 struct child_process cp_add = CHILD_PROCESS_INIT;
1593 struct child_process cp_diff = CHILD_PROCESS_INIT;
1594 struct child_process cp_apply = CHILD_PROCESS_INIT;
1595 struct strbuf out = STRBUF_INIT;
1597 cp_add.git_cmd = 1;
1598 strvec_push(&cp_add.args, "add");
1599 if (!include_untracked)
1600 strvec_push(&cp_add.args, "-u");
1601 if (include_untracked == INCLUDE_ALL_FILES)
1602 strvec_push(&cp_add.args, "--force");
1603 strvec_push(&cp_add.args, "--");
1604 add_pathspecs(&cp_add.args, ps);
1605 if (run_command(&cp_add)) {
1606 ret = -1;
1607 goto done;
1610 cp_diff.git_cmd = 1;
1611 strvec_pushl(&cp_diff.args, "diff-index", "-p",
1612 "--cached", "--binary", "HEAD", "--",
1613 NULL);
1614 add_pathspecs(&cp_diff.args, ps);
1615 if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1616 ret = -1;
1617 goto done;
1620 cp_apply.git_cmd = 1;
1621 strvec_pushl(&cp_apply.args, "apply", "--index",
1622 "-R", NULL);
1623 if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1624 NULL, 0)) {
1625 ret = -1;
1626 goto done;
1628 } else {
1629 struct child_process cp = CHILD_PROCESS_INIT;
1630 cp.git_cmd = 1;
1631 /* BUG: this nukes untracked files in the way */
1632 strvec_pushl(&cp.args, "reset", "--hard", "-q",
1633 "--no-recurse-submodules", NULL);
1634 if (run_command(&cp)) {
1635 ret = -1;
1636 goto done;
1640 if (keep_index == 1 && !is_null_oid(&info.i_tree)) {
1641 struct child_process cp = CHILD_PROCESS_INIT;
1643 cp.git_cmd = 1;
1644 strvec_pushl(&cp.args, "checkout", "--no-overlay",
1645 oid_to_hex(&info.i_tree), "--", NULL);
1646 if (!ps->nr)
1647 strvec_push(&cp.args, ":/");
1648 else
1649 add_pathspecs(&cp.args, ps);
1650 if (run_command(&cp)) {
1651 ret = -1;
1652 goto done;
1655 goto done;
1656 } else {
1657 struct child_process cp = CHILD_PROCESS_INIT;
1659 cp.git_cmd = 1;
1660 strvec_pushl(&cp.args, "apply", "-R", NULL);
1662 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1663 if (!quiet)
1664 fprintf_ln(stderr, _("Cannot remove "
1665 "worktree changes"));
1666 ret = -1;
1667 goto done;
1670 if (keep_index < 1) {
1671 struct child_process cp = CHILD_PROCESS_INIT;
1673 cp.git_cmd = 1;
1674 strvec_pushl(&cp.args, "reset", "-q", "--refresh", "--",
1675 NULL);
1676 add_pathspecs(&cp.args, ps);
1677 if (run_command(&cp)) {
1678 ret = -1;
1679 goto done;
1682 goto done;
1685 done:
1686 free_stash_info(&info);
1687 strbuf_release(&stash_msg_buf);
1688 return ret;
1691 static int push_stash(int argc, const char **argv, const char *prefix,
1692 int push_assumed)
1694 int force_assume = 0;
1695 int keep_index = -1;
1696 int only_staged = 0;
1697 int patch_mode = 0;
1698 int include_untracked = 0;
1699 int quiet = 0;
1700 int pathspec_file_nul = 0;
1701 const char *stash_msg = NULL;
1702 const char *pathspec_from_file = NULL;
1703 struct pathspec ps;
1704 struct option options[] = {
1705 OPT_BOOL('k', "keep-index", &keep_index,
1706 N_("keep index")),
1707 OPT_BOOL('S', "staged", &only_staged,
1708 N_("stash staged changes only")),
1709 OPT_BOOL('p', "patch", &patch_mode,
1710 N_("stash in patch mode")),
1711 OPT__QUIET(&quiet, N_("quiet mode")),
1712 OPT_BOOL('u', "include-untracked", &include_untracked,
1713 N_("include untracked files in stash")),
1714 OPT_SET_INT('a', "all", &include_untracked,
1715 N_("include ignore files"), 2),
1716 OPT_STRING('m', "message", &stash_msg, N_("message"),
1717 N_("stash message")),
1718 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1719 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1720 OPT_END()
1723 if (argc) {
1724 force_assume = !strcmp(argv[0], "-p");
1725 argc = parse_options(argc, argv, prefix, options,
1726 push_assumed ? git_stash_usage :
1727 git_stash_push_usage,
1728 PARSE_OPT_KEEP_DASHDASH);
1731 if (argc) {
1732 if (!strcmp(argv[0], "--")) {
1733 argc--;
1734 argv++;
1735 } else if (push_assumed && !force_assume) {
1736 die("subcommand wasn't specified; 'push' can't be assumed due to unexpected token '%s'",
1737 argv[0]);
1741 parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1742 prefix, argv);
1744 if (pathspec_from_file) {
1745 if (patch_mode)
1746 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1748 if (only_staged)
1749 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--staged");
1751 if (ps.nr)
1752 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1754 parse_pathspec_file(&ps, 0,
1755 PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1756 prefix, pathspec_from_file, pathspec_file_nul);
1757 } else if (pathspec_file_nul) {
1758 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1761 return do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
1762 include_untracked, only_staged);
1765 static int push_stash_unassumed(int argc, const char **argv, const char *prefix)
1767 return push_stash(argc, argv, prefix, 0);
1770 static int save_stash(int argc, const char **argv, const char *prefix)
1772 int keep_index = -1;
1773 int only_staged = 0;
1774 int patch_mode = 0;
1775 int include_untracked = 0;
1776 int quiet = 0;
1777 int ret = 0;
1778 const char *stash_msg = NULL;
1779 struct pathspec ps;
1780 struct strbuf stash_msg_buf = STRBUF_INIT;
1781 struct option options[] = {
1782 OPT_BOOL('k', "keep-index", &keep_index,
1783 N_("keep index")),
1784 OPT_BOOL('S', "staged", &only_staged,
1785 N_("stash staged changes only")),
1786 OPT_BOOL('p', "patch", &patch_mode,
1787 N_("stash in patch mode")),
1788 OPT__QUIET(&quiet, N_("quiet mode")),
1789 OPT_BOOL('u', "include-untracked", &include_untracked,
1790 N_("include untracked files in stash")),
1791 OPT_SET_INT('a', "all", &include_untracked,
1792 N_("include ignore files"), 2),
1793 OPT_STRING('m', "message", &stash_msg, "message",
1794 N_("stash message")),
1795 OPT_END()
1798 argc = parse_options(argc, argv, prefix, options,
1799 git_stash_save_usage,
1800 PARSE_OPT_KEEP_DASHDASH);
1802 if (argc)
1803 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
1805 memset(&ps, 0, sizeof(ps));
1806 ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
1807 patch_mode, include_untracked, only_staged);
1809 strbuf_release(&stash_msg_buf);
1810 return ret;
1813 int cmd_stash(int argc, const char **argv, const char *prefix)
1815 pid_t pid = getpid();
1816 const char *index_file;
1817 struct strvec args = STRVEC_INIT;
1818 parse_opt_subcommand_fn *fn = NULL;
1819 struct option options[] = {
1820 OPT_SUBCOMMAND("apply", &fn, apply_stash),
1821 OPT_SUBCOMMAND("clear", &fn, clear_stash),
1822 OPT_SUBCOMMAND("drop", &fn, drop_stash),
1823 OPT_SUBCOMMAND("pop", &fn, pop_stash),
1824 OPT_SUBCOMMAND("branch", &fn, branch_stash),
1825 OPT_SUBCOMMAND("list", &fn, list_stash),
1826 OPT_SUBCOMMAND("show", &fn, show_stash),
1827 OPT_SUBCOMMAND("store", &fn, store_stash),
1828 OPT_SUBCOMMAND("create", &fn, create_stash),
1829 OPT_SUBCOMMAND("push", &fn, push_stash_unassumed),
1830 OPT_SUBCOMMAND_F("save", &fn, save_stash, PARSE_OPT_NOCOMPLETE),
1831 OPT_END()
1834 git_config(git_stash_config, NULL);
1836 argc = parse_options(argc, argv, prefix, options, git_stash_usage,
1837 PARSE_OPT_SUBCOMMAND_OPTIONAL |
1838 PARSE_OPT_KEEP_UNKNOWN_OPT |
1839 PARSE_OPT_KEEP_DASHDASH);
1841 prepare_repo_settings(the_repository);
1842 the_repository->settings.command_requires_full_index = 0;
1844 index_file = get_index_file();
1845 strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
1846 (uintmax_t)pid);
1848 if (fn)
1849 return !!fn(argc, argv, prefix);
1850 else if (!argc)
1851 return !!push_stash_unassumed(0, NULL, prefix);
1853 /* Assume 'stash push' */
1854 strvec_push(&args, "push");
1855 strvec_pushv(&args, argv);
1856 return !!push_stash(args.nr, args.v, prefix, 1);