Merge branch 'jk/unused-annotation'
[git/debian.git] / builtin / stash.c
blob932c6173cfcaeb9113a620b5ed51111fba82b559
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 static const char * const git_stash_usage[] = {
25 N_("git stash list [<options>]"),
26 N_("git stash show [<options>] [<stash>]"),
27 N_("git stash drop [-q|--quiet] [<stash>]"),
28 N_("git stash ( pop | apply ) [--index] [-q|--quiet] [<stash>]"),
29 N_("git stash branch <branchname> [<stash>]"),
30 "git stash clear",
31 N_("git stash [push [-p|--patch] [-S|--staged] [-k|--[no-]keep-index] [-q|--quiet]\n"
32 " [-u|--include-untracked] [-a|--all] [-m|--message <message>]\n"
33 " [--pathspec-from-file=<file> [--pathspec-file-nul]]\n"
34 " [--] [<pathspec>...]]"),
35 N_("git stash save [-p|--patch] [-S|--staged] [-k|--[no-]keep-index] [-q|--quiet]\n"
36 " [-u|--include-untracked] [-a|--all] [<message>]"),
37 NULL
40 static const char * const git_stash_list_usage[] = {
41 N_("git stash list [<options>]"),
42 NULL
45 static const char * const git_stash_show_usage[] = {
46 N_("git stash show [<options>] [<stash>]"),
47 NULL
50 static const char * const git_stash_drop_usage[] = {
51 N_("git stash drop [-q|--quiet] [<stash>]"),
52 NULL
55 static const char * const git_stash_pop_usage[] = {
56 N_("git stash pop [--index] [-q|--quiet] [<stash>]"),
57 NULL
60 static const char * const git_stash_apply_usage[] = {
61 N_("git stash apply [--index] [-q|--quiet] [<stash>]"),
62 NULL
65 static const char * const git_stash_branch_usage[] = {
66 N_("git stash branch <branchname> [<stash>]"),
67 NULL
70 static const char * const git_stash_clear_usage[] = {
71 "git stash clear",
72 NULL
75 static const char * const git_stash_store_usage[] = {
76 N_("git stash store [-m|--message <message>] [-q|--quiet] <commit>"),
77 NULL
80 static const char * const git_stash_push_usage[] = {
81 N_("git stash [push [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
82 " [-u|--include-untracked] [-a|--all] [-m|--message <message>]\n"
83 " [--] [<pathspec>...]]"),
84 NULL
87 static const char * const git_stash_save_usage[] = {
88 N_("git stash save [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
89 " [-u|--include-untracked] [-a|--all] [<message>]"),
90 NULL
93 static const char ref_stash[] = "refs/stash";
94 static struct strbuf stash_index_path = STRBUF_INIT;
97 * w_commit is set to the commit containing the working tree
98 * b_commit is set to the base commit
99 * i_commit is set to the commit containing the index tree
100 * u_commit is set to the commit containing the untracked files tree
101 * w_tree is set to the working tree
102 * b_tree is set to the base tree
103 * i_tree is set to the index tree
104 * u_tree is set to the untracked files tree
106 struct stash_info {
107 struct object_id w_commit;
108 struct object_id b_commit;
109 struct object_id i_commit;
110 struct object_id u_commit;
111 struct object_id w_tree;
112 struct object_id b_tree;
113 struct object_id i_tree;
114 struct object_id u_tree;
115 struct strbuf revision;
116 int is_stash_ref;
117 int has_u;
120 #define STASH_INFO_INIT { \
121 .revision = STRBUF_INIT, \
124 static void free_stash_info(struct stash_info *info)
126 strbuf_release(&info->revision);
129 static void assert_stash_like(struct stash_info *info, const char *revision)
131 if (get_oidf(&info->b_commit, "%s^1", revision) ||
132 get_oidf(&info->w_tree, "%s:", revision) ||
133 get_oidf(&info->b_tree, "%s^1:", revision) ||
134 get_oidf(&info->i_tree, "%s^2:", revision))
135 die(_("'%s' is not a stash-like commit"), revision);
138 static int get_stash_info(struct stash_info *info, int argc, const char **argv)
140 int ret;
141 char *end_of_rev;
142 char *expanded_ref;
143 const char *revision;
144 const char *commit = NULL;
145 struct object_id dummy;
146 struct strbuf symbolic = STRBUF_INIT;
148 if (argc > 1) {
149 int i;
150 struct strbuf refs_msg = STRBUF_INIT;
152 for (i = 0; i < argc; i++)
153 strbuf_addf(&refs_msg, " '%s'", argv[i]);
155 fprintf_ln(stderr, _("Too many revisions specified:%s"),
156 refs_msg.buf);
157 strbuf_release(&refs_msg);
159 return -1;
162 if (argc == 1)
163 commit = argv[0];
165 if (!commit) {
166 if (!ref_exists(ref_stash)) {
167 fprintf_ln(stderr, _("No stash entries found."));
168 return -1;
171 strbuf_addf(&info->revision, "%s@{0}", ref_stash);
172 } else if (strspn(commit, "0123456789") == strlen(commit)) {
173 strbuf_addf(&info->revision, "%s@{%s}", ref_stash, commit);
174 } else {
175 strbuf_addstr(&info->revision, commit);
178 revision = info->revision.buf;
180 if (get_oid(revision, &info->w_commit))
181 return error(_("%s is not a valid reference"), revision);
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 break;
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_pushl(&cp.args, "reset", "--quiet", "--refresh", NULL);
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, "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, "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 clean, 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 tree *head, *merge, *merge_base;
501 struct lock_file lock = LOCK_INIT;
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";
544 o.ancestor = "Stash base";
546 if (oideq(&info->b_tree, &c_tree))
547 o.branch1 = "Version stash was based on";
549 if (quiet)
550 o.verbosity = 0;
552 if (o.verbosity >= 3)
553 printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
555 head = lookup_tree(o.repo, &c_tree);
556 merge = lookup_tree(o.repo, &info->w_tree);
557 merge_base = lookup_tree(o.repo, &info->b_tree);
559 repo_hold_locked_index(o.repo, &lock, LOCK_DIE_ON_ERROR);
560 clean = merge_ort_nonrecursive(&o, head, merge, merge_base);
563 * If 'clean' >= 0, reverse the value for 'ret' so 'ret' is 0 when the
564 * merge was clean, and nonzero if the merge was unclean or encountered
565 * an error.
567 ret = clean >= 0 ? !clean : clean;
569 if (ret < 0)
570 rollback_lock_file(&lock);
571 else if (write_locked_index(o.repo->index, &lock,
572 COMMIT_LOCK | SKIP_IF_UNCHANGED))
573 ret = error(_("could not write index"));
575 if (ret) {
576 rerere(0);
578 if (index)
579 fprintf_ln(stderr, _("Index was not unstashed."));
581 goto restore_untracked;
584 if (has_index) {
585 if (reset_tree(&index_tree, 0, 0))
586 ret = -1;
587 } else {
588 unstage_changes_unless_new(&c_tree);
591 restore_untracked:
592 if (info->has_u && restore_untracked(&info->u_tree))
593 ret = error(_("could not restore untracked files from stash"));
595 if (!quiet) {
596 struct child_process cp = CHILD_PROCESS_INIT;
599 * Status is quite simple and could be replaced with calls to
600 * wt_status in the future, but it adds complexities which may
601 * require more tests.
603 cp.git_cmd = 1;
604 cp.dir = prefix;
605 strvec_pushf(&cp.env, GIT_WORK_TREE_ENVIRONMENT"=%s",
606 absolute_path(get_git_work_tree()));
607 strvec_pushf(&cp.env, GIT_DIR_ENVIRONMENT"=%s",
608 absolute_path(get_git_dir()));
609 strvec_push(&cp.args, "status");
610 run_command(&cp);
613 return ret;
616 static int apply_stash(int argc, const char **argv, const char *prefix)
618 int ret = -1;
619 int quiet = 0;
620 int index = 0;
621 struct stash_info info = STASH_INFO_INIT;
622 struct option options[] = {
623 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
624 OPT_BOOL(0, "index", &index,
625 N_("attempt to recreate the index")),
626 OPT_END()
629 argc = parse_options(argc, argv, prefix, options,
630 git_stash_apply_usage, 0);
632 if (get_stash_info(&info, argc, argv))
633 goto cleanup;
635 ret = do_apply_stash(prefix, &info, index, quiet);
636 cleanup:
637 free_stash_info(&info);
638 return ret;
641 static int reject_reflog_ent(struct object_id *UNUSED(ooid),
642 struct object_id *UNUSED(noid),
643 const char *UNUSED(email),
644 timestamp_t UNUSED(timestamp),
645 int UNUSED(tz), const char *UNUSED(message),
646 void *UNUSED(cb_data))
648 return 1;
651 static int reflog_is_empty(const char *refname)
653 return !for_each_reflog_ent(refname, reject_reflog_ent, NULL);
656 static int do_drop_stash(struct stash_info *info, int quiet)
658 if (!reflog_delete(info->revision.buf,
659 EXPIRE_REFLOGS_REWRITE | EXPIRE_REFLOGS_UPDATE_REF,
660 0)) {
661 if (!quiet)
662 printf_ln(_("Dropped %s (%s)"), info->revision.buf,
663 oid_to_hex(&info->w_commit));
664 } else {
665 return error(_("%s: Could not drop stash entry"),
666 info->revision.buf);
669 if (reflog_is_empty(ref_stash))
670 do_clear_stash();
672 return 0;
675 static int get_stash_info_assert(struct stash_info *info, int argc,
676 const char **argv)
678 int ret = get_stash_info(info, argc, argv);
680 if (ret < 0)
681 return ret;
683 if (!info->is_stash_ref)
684 return error(_("'%s' is not a stash reference"), info->revision.buf);
686 return 0;
689 static int drop_stash(int argc, const char **argv, const char *prefix)
691 int ret = -1;
692 int quiet = 0;
693 struct stash_info info = STASH_INFO_INIT;
694 struct option options[] = {
695 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
696 OPT_END()
699 argc = parse_options(argc, argv, prefix, options,
700 git_stash_drop_usage, 0);
702 if (get_stash_info_assert(&info, argc, argv))
703 goto cleanup;
705 ret = do_drop_stash(&info, quiet);
706 cleanup:
707 free_stash_info(&info);
708 return ret;
711 static int pop_stash(int argc, const char **argv, const char *prefix)
713 int ret = -1;
714 int index = 0;
715 int quiet = 0;
716 struct stash_info info = STASH_INFO_INIT;
717 struct option options[] = {
718 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
719 OPT_BOOL(0, "index", &index,
720 N_("attempt to recreate the index")),
721 OPT_END()
724 argc = parse_options(argc, argv, prefix, options,
725 git_stash_pop_usage, 0);
727 if (get_stash_info_assert(&info, argc, argv))
728 goto cleanup;
730 if ((ret = do_apply_stash(prefix, &info, index, quiet)))
731 printf_ln(_("The stash entry is kept in case "
732 "you need it again."));
733 else
734 ret = do_drop_stash(&info, quiet);
736 cleanup:
737 free_stash_info(&info);
738 return ret;
741 static int branch_stash(int argc, const char **argv, const char *prefix)
743 int ret = -1;
744 const char *branch = NULL;
745 struct stash_info info = STASH_INFO_INIT;
746 struct child_process cp = CHILD_PROCESS_INIT;
747 struct option options[] = {
748 OPT_END()
751 argc = parse_options(argc, argv, prefix, options,
752 git_stash_branch_usage, 0);
754 if (!argc) {
755 fprintf_ln(stderr, _("No branch name specified"));
756 return -1;
759 branch = argv[0];
761 if (get_stash_info(&info, argc - 1, argv + 1))
762 goto cleanup;
764 cp.git_cmd = 1;
765 strvec_pushl(&cp.args, "checkout", "-b", NULL);
766 strvec_push(&cp.args, branch);
767 strvec_push(&cp.args, oid_to_hex(&info.b_commit));
768 ret = run_command(&cp);
769 if (!ret)
770 ret = do_apply_stash(prefix, &info, 1, 0);
771 if (!ret && info.is_stash_ref)
772 ret = do_drop_stash(&info, 0);
774 cleanup:
775 free_stash_info(&info);
776 return ret;
779 static int list_stash(int argc, const char **argv, const char *prefix)
781 struct child_process cp = CHILD_PROCESS_INIT;
782 struct option options[] = {
783 OPT_END()
786 argc = parse_options(argc, argv, prefix, options,
787 git_stash_list_usage,
788 PARSE_OPT_KEEP_UNKNOWN_OPT);
790 if (!ref_exists(ref_stash))
791 return 0;
793 cp.git_cmd = 1;
794 strvec_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
795 "--first-parent", NULL);
796 strvec_pushv(&cp.args, argv);
797 strvec_push(&cp.args, ref_stash);
798 strvec_push(&cp.args, "--");
799 return run_command(&cp);
802 static int show_stat = 1;
803 static int show_patch;
804 static int show_include_untracked;
806 static int git_stash_config(const char *var, const char *value, void *cb)
808 if (!strcmp(var, "stash.showstat")) {
809 show_stat = git_config_bool(var, value);
810 return 0;
812 if (!strcmp(var, "stash.showpatch")) {
813 show_patch = git_config_bool(var, value);
814 return 0;
816 if (!strcmp(var, "stash.showincludeuntracked")) {
817 show_include_untracked = git_config_bool(var, value);
818 return 0;
820 return git_diff_basic_config(var, value, cb);
823 static void diff_include_untracked(const struct stash_info *info, struct diff_options *diff_opt)
825 const struct object_id *oid[] = { &info->w_commit, &info->u_tree };
826 struct tree *tree[ARRAY_SIZE(oid)];
827 struct tree_desc tree_desc[ARRAY_SIZE(oid)];
828 struct unpack_trees_options unpack_tree_opt = { 0 };
829 int i;
831 for (i = 0; i < ARRAY_SIZE(oid); i++) {
832 tree[i] = parse_tree_indirect(oid[i]);
833 if (parse_tree(tree[i]) < 0)
834 die(_("failed to parse tree"));
835 init_tree_desc(&tree_desc[i], tree[i]->buffer, tree[i]->size);
838 unpack_tree_opt.head_idx = -1;
839 unpack_tree_opt.src_index = &the_index;
840 unpack_tree_opt.dst_index = &the_index;
841 unpack_tree_opt.merge = 1;
842 unpack_tree_opt.fn = stash_worktree_untracked_merge;
844 if (unpack_trees(ARRAY_SIZE(tree_desc), tree_desc, &unpack_tree_opt))
845 die(_("failed to unpack trees"));
847 do_diff_cache(&info->b_commit, diff_opt);
850 static int show_stash(int argc, const char **argv, const char *prefix)
852 int i;
853 int ret = -1;
854 struct stash_info info = STASH_INFO_INIT;
855 struct rev_info rev;
856 struct strvec stash_args = STRVEC_INIT;
857 struct strvec revision_args = STRVEC_INIT;
858 enum {
859 UNTRACKED_NONE,
860 UNTRACKED_INCLUDE,
861 UNTRACKED_ONLY
862 } show_untracked = show_include_untracked ? UNTRACKED_INCLUDE : UNTRACKED_NONE;
863 struct option options[] = {
864 OPT_SET_INT('u', "include-untracked", &show_untracked,
865 N_("include untracked files in the stash"),
866 UNTRACKED_INCLUDE),
867 OPT_SET_INT_F(0, "only-untracked", &show_untracked,
868 N_("only show untracked files in the stash"),
869 UNTRACKED_ONLY, PARSE_OPT_NONEG),
870 OPT_END()
872 int do_usage = 0;
874 init_diff_ui_defaults();
875 git_config(git_diff_ui_config, NULL);
876 init_revisions(&rev, prefix);
878 argc = parse_options(argc, argv, prefix, options, git_stash_show_usage,
879 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
880 PARSE_OPT_KEEP_DASHDASH);
882 strvec_push(&revision_args, argv[0]);
883 for (i = 1; i < argc; i++) {
884 if (argv[i][0] != '-')
885 strvec_push(&stash_args, argv[i]);
886 else
887 strvec_push(&revision_args, argv[i]);
890 if (get_stash_info(&info, stash_args.nr, stash_args.v))
891 goto cleanup;
894 * The config settings are applied only if there are not passed
895 * any options.
897 if (revision_args.nr == 1) {
898 if (show_stat)
899 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
901 if (show_patch)
902 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
904 if (!show_stat && !show_patch) {
905 ret = 0;
906 goto cleanup;
910 argc = setup_revisions(revision_args.nr, revision_args.v, &rev, NULL);
911 if (argc > 1)
912 goto usage;
913 if (!rev.diffopt.output_format) {
914 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
915 diff_setup_done(&rev.diffopt);
918 rev.diffopt.flags.recursive = 1;
919 setup_diff_pager(&rev.diffopt);
920 switch (show_untracked) {
921 case UNTRACKED_NONE:
922 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
923 break;
924 case UNTRACKED_ONLY:
925 if (info.has_u)
926 diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
927 break;
928 case UNTRACKED_INCLUDE:
929 if (info.has_u)
930 diff_include_untracked(&info, &rev.diffopt);
931 else
932 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
933 break;
935 log_tree_diff_flush(&rev);
937 ret = diff_result_code(&rev.diffopt, 0);
938 cleanup:
939 strvec_clear(&stash_args);
940 free_stash_info(&info);
941 release_revisions(&rev);
942 if (do_usage)
943 usage_with_options(git_stash_show_usage, options);
944 return ret;
945 usage:
946 do_usage = 1;
947 goto cleanup;
950 static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
951 int quiet)
953 if (!stash_msg)
954 stash_msg = "Created via \"git stash store\".";
956 if (update_ref(stash_msg, ref_stash, w_commit, NULL,
957 REF_FORCE_CREATE_REFLOG,
958 quiet ? UPDATE_REFS_QUIET_ON_ERR :
959 UPDATE_REFS_MSG_ON_ERR)) {
960 if (!quiet) {
961 fprintf_ln(stderr, _("Cannot update %s with %s"),
962 ref_stash, oid_to_hex(w_commit));
964 return -1;
967 return 0;
970 static int store_stash(int argc, const char **argv, const char *prefix)
972 int quiet = 0;
973 const char *stash_msg = NULL;
974 struct object_id obj;
975 struct object_context dummy;
976 struct option options[] = {
977 OPT__QUIET(&quiet, N_("be quiet")),
978 OPT_STRING('m', "message", &stash_msg, "message",
979 N_("stash message")),
980 OPT_END()
983 argc = parse_options(argc, argv, prefix, options,
984 git_stash_store_usage,
985 PARSE_OPT_KEEP_UNKNOWN_OPT);
987 if (argc != 1) {
988 if (!quiet)
989 fprintf_ln(stderr, _("\"git stash store\" requires one "
990 "<commit> argument"));
991 return -1;
994 if (get_oid_with_context(the_repository,
995 argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
996 &dummy)) {
997 if (!quiet)
998 fprintf_ln(stderr, _("Cannot update %s with %s"),
999 ref_stash, argv[0]);
1000 return -1;
1003 return do_store_stash(&obj, stash_msg, quiet);
1006 static void add_pathspecs(struct strvec *args,
1007 const struct pathspec *ps) {
1008 int i;
1010 for (i = 0; i < ps->nr; i++)
1011 strvec_push(args, ps->items[i].original);
1015 * `untracked_files` will be filled with the names of untracked files.
1016 * The return value is:
1018 * = 0 if there are not any untracked files
1019 * > 0 if there are untracked files
1021 static int get_untracked_files(const struct pathspec *ps, int include_untracked,
1022 struct strbuf *untracked_files)
1024 int i;
1025 int found = 0;
1026 struct dir_struct dir = DIR_INIT;
1028 if (include_untracked != INCLUDE_ALL_FILES)
1029 setup_standard_excludes(&dir);
1031 fill_directory(&dir, the_repository->index, ps);
1032 for (i = 0; i < dir.nr; i++) {
1033 struct dir_entry *ent = dir.entries[i];
1034 found++;
1035 strbuf_addstr(untracked_files, ent->name);
1036 /* NUL-terminate: will be fed to update-index -z */
1037 strbuf_addch(untracked_files, '\0');
1040 dir_clear(&dir);
1041 return found;
1045 * The return value of `check_changes_tracked_files()` can be:
1047 * < 0 if there was an error
1048 * = 0 if there are no changes.
1049 * > 0 if there are changes.
1051 static int check_changes_tracked_files(const struct pathspec *ps)
1053 int result;
1054 struct rev_info rev;
1055 struct object_id dummy;
1056 int ret = 0;
1058 /* No initial commit. */
1059 if (get_oid("HEAD", &dummy))
1060 return -1;
1062 if (read_cache() < 0)
1063 return -1;
1065 init_revisions(&rev, NULL);
1066 copy_pathspec(&rev.prune_data, ps);
1068 rev.diffopt.flags.quick = 1;
1069 rev.diffopt.flags.ignore_submodules = 1;
1070 rev.abbrev = 0;
1072 add_head_to_pending(&rev);
1073 diff_setup_done(&rev.diffopt);
1075 result = run_diff_index(&rev, 1);
1076 if (diff_result_code(&rev.diffopt, result)) {
1077 ret = 1;
1078 goto done;
1081 result = run_diff_files(&rev, 0);
1082 if (diff_result_code(&rev.diffopt, result)) {
1083 ret = 1;
1084 goto done;
1087 done:
1088 release_revisions(&rev);
1089 return ret;
1093 * The function will fill `untracked_files` with the names of untracked files
1094 * It will return 1 if there were any changes and 0 if there were not.
1096 static int check_changes(const struct pathspec *ps, int include_untracked,
1097 struct strbuf *untracked_files)
1099 int ret = 0;
1100 if (check_changes_tracked_files(ps))
1101 ret = 1;
1103 if (include_untracked && get_untracked_files(ps, include_untracked,
1104 untracked_files))
1105 ret = 1;
1107 return ret;
1110 static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
1111 struct strbuf files)
1113 int ret = 0;
1114 struct strbuf untracked_msg = STRBUF_INIT;
1115 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1116 struct index_state istate = { NULL };
1118 cp_upd_index.git_cmd = 1;
1119 strvec_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
1120 "--remove", "--stdin", NULL);
1121 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1122 stash_index_path.buf);
1124 strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
1125 if (pipe_command(&cp_upd_index, files.buf, files.len, NULL, 0,
1126 NULL, 0)) {
1127 ret = -1;
1128 goto done;
1131 if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
1132 NULL)) {
1133 ret = -1;
1134 goto done;
1137 if (commit_tree(untracked_msg.buf, untracked_msg.len,
1138 &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
1139 ret = -1;
1140 goto done;
1143 done:
1144 discard_index(&istate);
1145 strbuf_release(&untracked_msg);
1146 remove_path(stash_index_path.buf);
1147 return ret;
1150 static int stash_staged(struct stash_info *info, struct strbuf *out_patch,
1151 int quiet)
1153 int ret = 0;
1154 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1155 struct index_state istate = { NULL };
1157 if (write_index_as_tree(&info->w_tree, &istate, the_repository->index_file,
1158 0, NULL)) {
1159 ret = -1;
1160 goto done;
1163 cp_diff_tree.git_cmd = 1;
1164 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1165 oid_to_hex(&info->w_tree), "--", NULL);
1166 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1167 ret = -1;
1168 goto done;
1171 if (!out_patch->len) {
1172 if (!quiet)
1173 fprintf_ln(stderr, _("No staged changes"));
1174 ret = 1;
1177 done:
1178 discard_index(&istate);
1179 return ret;
1182 static int stash_patch(struct stash_info *info, const struct pathspec *ps,
1183 struct strbuf *out_patch, int quiet)
1185 int ret = 0;
1186 struct child_process cp_read_tree = CHILD_PROCESS_INIT;
1187 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1188 struct index_state istate = { NULL };
1189 char *old_index_env = NULL, *old_repo_index_file;
1191 remove_path(stash_index_path.buf);
1193 cp_read_tree.git_cmd = 1;
1194 strvec_pushl(&cp_read_tree.args, "read-tree", "HEAD", NULL);
1195 strvec_pushf(&cp_read_tree.env, "GIT_INDEX_FILE=%s",
1196 stash_index_path.buf);
1197 if (run_command(&cp_read_tree)) {
1198 ret = -1;
1199 goto done;
1202 /* Find out what the user wants. */
1203 old_repo_index_file = the_repository->index_file;
1204 the_repository->index_file = stash_index_path.buf;
1205 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
1206 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
1208 ret = run_add_interactive(NULL, "--patch=stash", ps);
1210 the_repository->index_file = old_repo_index_file;
1211 if (old_index_env && *old_index_env)
1212 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
1213 else
1214 unsetenv(INDEX_ENVIRONMENT);
1215 FREE_AND_NULL(old_index_env);
1217 /* State of the working tree. */
1218 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1219 NULL)) {
1220 ret = -1;
1221 goto done;
1224 cp_diff_tree.git_cmd = 1;
1225 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1226 oid_to_hex(&info->w_tree), "--", NULL);
1227 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1228 ret = -1;
1229 goto done;
1232 if (!out_patch->len) {
1233 if (!quiet)
1234 fprintf_ln(stderr, _("No changes selected"));
1235 ret = 1;
1238 done:
1239 discard_index(&istate);
1240 remove_path(stash_index_path.buf);
1241 return ret;
1244 static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
1246 int ret = 0;
1247 struct rev_info rev;
1248 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1249 struct strbuf diff_output = STRBUF_INIT;
1250 struct index_state istate = { NULL };
1252 init_revisions(&rev, NULL);
1253 copy_pathspec(&rev.prune_data, ps);
1255 set_alternate_index_output(stash_index_path.buf);
1256 if (reset_tree(&info->i_tree, 0, 0)) {
1257 ret = -1;
1258 goto done;
1260 set_alternate_index_output(NULL);
1262 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1263 rev.diffopt.format_callback = add_diff_to_buf;
1264 rev.diffopt.format_callback_data = &diff_output;
1266 if (read_cache_preload(&rev.diffopt.pathspec) < 0) {
1267 ret = -1;
1268 goto done;
1271 add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1272 "");
1273 if (run_diff_index(&rev, 0)) {
1274 ret = -1;
1275 goto done;
1278 cp_upd_index.git_cmd = 1;
1279 strvec_pushl(&cp_upd_index.args, "update-index",
1280 "--ignore-skip-worktree-entries",
1281 "-z", "--add", "--remove", "--stdin", NULL);
1282 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1283 stash_index_path.buf);
1285 if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1286 NULL, 0, NULL, 0)) {
1287 ret = -1;
1288 goto done;
1291 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1292 NULL)) {
1293 ret = -1;
1294 goto done;
1297 done:
1298 discard_index(&istate);
1299 release_revisions(&rev);
1300 strbuf_release(&diff_output);
1301 remove_path(stash_index_path.buf);
1302 return ret;
1305 static int do_create_stash(const struct pathspec *ps, struct strbuf *stash_msg_buf,
1306 int include_untracked, int patch_mode, int only_staged,
1307 struct stash_info *info, struct strbuf *patch,
1308 int quiet)
1310 int ret = 0;
1311 int flags = 0;
1312 int untracked_commit_option = 0;
1313 const char *head_short_sha1 = NULL;
1314 const char *branch_ref = NULL;
1315 const char *branch_name = "(no branch)";
1316 struct commit *head_commit = NULL;
1317 struct commit_list *parents = NULL;
1318 struct strbuf msg = STRBUF_INIT;
1319 struct strbuf commit_tree_label = STRBUF_INIT;
1320 struct strbuf untracked_files = STRBUF_INIT;
1322 prepare_fallback_ident("git stash", "git@stash");
1324 read_cache_preload(NULL);
1325 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0) < 0) {
1326 ret = -1;
1327 goto done;
1330 if (get_oid("HEAD", &info->b_commit)) {
1331 if (!quiet)
1332 fprintf_ln(stderr, _("You do not have "
1333 "the initial commit yet"));
1334 ret = -1;
1335 goto done;
1336 } else {
1337 head_commit = lookup_commit(the_repository, &info->b_commit);
1340 if (!check_changes(ps, include_untracked, &untracked_files)) {
1341 ret = 1;
1342 goto done;
1345 branch_ref = resolve_ref_unsafe("HEAD", 0, NULL, &flags);
1346 if (flags & REF_ISSYMREF)
1347 skip_prefix(branch_ref, "refs/heads/", &branch_name);
1348 head_short_sha1 = find_unique_abbrev(&head_commit->object.oid,
1349 DEFAULT_ABBREV);
1350 strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1351 pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1353 strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1354 commit_list_insert(head_commit, &parents);
1355 if (write_cache_as_tree(&info->i_tree, 0, NULL) ||
1356 commit_tree(commit_tree_label.buf, commit_tree_label.len,
1357 &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1358 if (!quiet)
1359 fprintf_ln(stderr, _("Cannot save the current "
1360 "index state"));
1361 ret = -1;
1362 goto done;
1365 if (include_untracked) {
1366 if (save_untracked_files(info, &msg, untracked_files)) {
1367 if (!quiet)
1368 fprintf_ln(stderr, _("Cannot save "
1369 "the untracked files"));
1370 ret = -1;
1371 goto done;
1373 untracked_commit_option = 1;
1375 if (patch_mode) {
1376 ret = stash_patch(info, ps, patch, quiet);
1377 if (ret < 0) {
1378 if (!quiet)
1379 fprintf_ln(stderr, _("Cannot save the current "
1380 "worktree state"));
1381 goto done;
1382 } else if (ret > 0) {
1383 goto done;
1385 } else if (only_staged) {
1386 ret = stash_staged(info, patch, quiet);
1387 if (ret < 0) {
1388 if (!quiet)
1389 fprintf_ln(stderr, _("Cannot save the current "
1390 "staged state"));
1391 goto done;
1392 } else if (ret > 0) {
1393 goto done;
1395 } else {
1396 if (stash_working_tree(info, ps)) {
1397 if (!quiet)
1398 fprintf_ln(stderr, _("Cannot save the current "
1399 "worktree state"));
1400 ret = -1;
1401 goto done;
1405 if (!stash_msg_buf->len)
1406 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1407 else
1408 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1411 * `parents` will be empty after calling `commit_tree()`, so there is
1412 * no need to call `free_commit_list()`
1414 parents = NULL;
1415 if (untracked_commit_option)
1416 commit_list_insert(lookup_commit(the_repository,
1417 &info->u_commit),
1418 &parents);
1419 commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1420 &parents);
1421 commit_list_insert(head_commit, &parents);
1423 if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1424 parents, &info->w_commit, NULL, NULL)) {
1425 if (!quiet)
1426 fprintf_ln(stderr, _("Cannot record "
1427 "working tree state"));
1428 ret = -1;
1429 goto done;
1432 done:
1433 strbuf_release(&commit_tree_label);
1434 strbuf_release(&msg);
1435 strbuf_release(&untracked_files);
1436 return ret;
1439 static int create_stash(int argc, const char **argv, const char *prefix)
1441 int ret;
1442 struct strbuf stash_msg_buf = STRBUF_INIT;
1443 struct stash_info info = STASH_INFO_INIT;
1444 struct pathspec ps;
1446 /* Starting with argv[1], since argv[0] is "create" */
1447 strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
1449 memset(&ps, 0, sizeof(ps));
1450 if (!check_changes_tracked_files(&ps))
1451 return 0;
1453 ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, 0, &info,
1454 NULL, 0);
1455 if (!ret)
1456 printf_ln("%s", oid_to_hex(&info.w_commit));
1458 free_stash_info(&info);
1459 strbuf_release(&stash_msg_buf);
1460 return ret;
1463 static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int quiet,
1464 int keep_index, int patch_mode, int include_untracked, int only_staged)
1466 int ret = 0;
1467 struct stash_info info = STASH_INFO_INIT;
1468 struct strbuf patch = STRBUF_INIT;
1469 struct strbuf stash_msg_buf = STRBUF_INIT;
1470 struct strbuf untracked_files = STRBUF_INIT;
1472 if (patch_mode && keep_index == -1)
1473 keep_index = 1;
1475 if (patch_mode && include_untracked) {
1476 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1477 " or --all at the same time"));
1478 ret = -1;
1479 goto done;
1482 /* --patch overrides --staged */
1483 if (patch_mode)
1484 only_staged = 0;
1486 if (only_staged && include_untracked) {
1487 fprintf_ln(stderr, _("Can't use --staged and --include-untracked"
1488 " or --all at the same time"));
1489 ret = -1;
1490 goto done;
1493 read_cache_preload(NULL);
1494 if (!include_untracked && ps->nr) {
1495 int i;
1496 char *ps_matched = xcalloc(ps->nr, 1);
1498 /* TODO: audit for interaction with sparse-index. */
1499 ensure_full_index(&the_index);
1500 for (i = 0; i < active_nr; i++)
1501 ce_path_match(&the_index, active_cache[i], ps,
1502 ps_matched);
1504 if (report_path_error(ps_matched, ps)) {
1505 fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1506 ret = -1;
1507 free(ps_matched);
1508 goto done;
1510 free(ps_matched);
1513 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0)) {
1514 ret = -1;
1515 goto done;
1518 if (!check_changes(ps, include_untracked, &untracked_files)) {
1519 if (!quiet)
1520 printf_ln(_("No local changes to save"));
1521 goto done;
1524 if (!reflog_exists(ref_stash) && do_clear_stash()) {
1525 ret = -1;
1526 if (!quiet)
1527 fprintf_ln(stderr, _("Cannot initialize stash"));
1528 goto done;
1531 if (stash_msg)
1532 strbuf_addstr(&stash_msg_buf, stash_msg);
1533 if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode, only_staged,
1534 &info, &patch, quiet)) {
1535 ret = -1;
1536 goto done;
1539 if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1540 ret = -1;
1541 if (!quiet)
1542 fprintf_ln(stderr, _("Cannot save the current status"));
1543 goto done;
1546 if (!quiet)
1547 printf_ln(_("Saved working directory and index state %s"),
1548 stash_msg_buf.buf);
1550 if (!(patch_mode || only_staged)) {
1551 if (include_untracked && !ps->nr) {
1552 struct child_process cp = CHILD_PROCESS_INIT;
1554 cp.git_cmd = 1;
1555 if (startup_info->original_cwd) {
1556 cp.dir = startup_info->original_cwd;
1557 strvec_pushf(&cp.env, "%s=%s",
1558 GIT_WORK_TREE_ENVIRONMENT,
1559 the_repository->worktree);
1561 strvec_pushl(&cp.args, "clean", "--force",
1562 "--quiet", "-d", ":/", NULL);
1563 if (include_untracked == INCLUDE_ALL_FILES)
1564 strvec_push(&cp.args, "-x");
1565 if (run_command(&cp)) {
1566 ret = -1;
1567 goto done;
1570 discard_cache();
1571 if (ps->nr) {
1572 struct child_process cp_add = CHILD_PROCESS_INIT;
1573 struct child_process cp_diff = CHILD_PROCESS_INIT;
1574 struct child_process cp_apply = CHILD_PROCESS_INIT;
1575 struct strbuf out = STRBUF_INIT;
1577 cp_add.git_cmd = 1;
1578 strvec_push(&cp_add.args, "add");
1579 if (!include_untracked)
1580 strvec_push(&cp_add.args, "-u");
1581 if (include_untracked == INCLUDE_ALL_FILES)
1582 strvec_push(&cp_add.args, "--force");
1583 strvec_push(&cp_add.args, "--");
1584 add_pathspecs(&cp_add.args, ps);
1585 if (run_command(&cp_add)) {
1586 ret = -1;
1587 goto done;
1590 cp_diff.git_cmd = 1;
1591 strvec_pushl(&cp_diff.args, "diff-index", "-p",
1592 "--cached", "--binary", "HEAD", "--",
1593 NULL);
1594 add_pathspecs(&cp_diff.args, ps);
1595 if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1596 ret = -1;
1597 goto done;
1600 cp_apply.git_cmd = 1;
1601 strvec_pushl(&cp_apply.args, "apply", "--index",
1602 "-R", NULL);
1603 if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1604 NULL, 0)) {
1605 ret = -1;
1606 goto done;
1608 } else {
1609 struct child_process cp = CHILD_PROCESS_INIT;
1610 cp.git_cmd = 1;
1611 /* BUG: this nukes untracked files in the way */
1612 strvec_pushl(&cp.args, "reset", "--hard", "-q",
1613 "--no-recurse-submodules", NULL);
1614 if (run_command(&cp)) {
1615 ret = -1;
1616 goto done;
1620 if (keep_index == 1 && !is_null_oid(&info.i_tree)) {
1621 struct child_process cp = CHILD_PROCESS_INIT;
1623 cp.git_cmd = 1;
1624 strvec_pushl(&cp.args, "checkout", "--no-overlay",
1625 oid_to_hex(&info.i_tree), "--", NULL);
1626 if (!ps->nr)
1627 strvec_push(&cp.args, ":/");
1628 else
1629 add_pathspecs(&cp.args, ps);
1630 if (run_command(&cp)) {
1631 ret = -1;
1632 goto done;
1635 goto done;
1636 } else {
1637 struct child_process cp = CHILD_PROCESS_INIT;
1639 cp.git_cmd = 1;
1640 strvec_pushl(&cp.args, "apply", "-R", NULL);
1642 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1643 if (!quiet)
1644 fprintf_ln(stderr, _("Cannot remove "
1645 "worktree changes"));
1646 ret = -1;
1647 goto done;
1650 if (keep_index < 1) {
1651 struct child_process cp = CHILD_PROCESS_INIT;
1653 cp.git_cmd = 1;
1654 strvec_pushl(&cp.args, "reset", "-q", "--refresh", "--",
1655 NULL);
1656 add_pathspecs(&cp.args, ps);
1657 if (run_command(&cp)) {
1658 ret = -1;
1659 goto done;
1662 goto done;
1665 done:
1666 free_stash_info(&info);
1667 strbuf_release(&stash_msg_buf);
1668 return ret;
1671 static int push_stash(int argc, const char **argv, const char *prefix,
1672 int push_assumed)
1674 int force_assume = 0;
1675 int keep_index = -1;
1676 int only_staged = 0;
1677 int patch_mode = 0;
1678 int include_untracked = 0;
1679 int quiet = 0;
1680 int pathspec_file_nul = 0;
1681 const char *stash_msg = NULL;
1682 const char *pathspec_from_file = NULL;
1683 struct pathspec ps;
1684 struct option options[] = {
1685 OPT_BOOL('k', "keep-index", &keep_index,
1686 N_("keep index")),
1687 OPT_BOOL('S', "staged", &only_staged,
1688 N_("stash staged changes only")),
1689 OPT_BOOL('p', "patch", &patch_mode,
1690 N_("stash in patch mode")),
1691 OPT__QUIET(&quiet, N_("quiet mode")),
1692 OPT_BOOL('u', "include-untracked", &include_untracked,
1693 N_("include untracked files in stash")),
1694 OPT_SET_INT('a', "all", &include_untracked,
1695 N_("include ignore files"), 2),
1696 OPT_STRING('m', "message", &stash_msg, N_("message"),
1697 N_("stash message")),
1698 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1699 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1700 OPT_END()
1703 if (argc) {
1704 force_assume = !strcmp(argv[0], "-p");
1705 argc = parse_options(argc, argv, prefix, options,
1706 push_assumed ? git_stash_usage :
1707 git_stash_push_usage,
1708 PARSE_OPT_KEEP_DASHDASH);
1711 if (argc) {
1712 if (!strcmp(argv[0], "--")) {
1713 argc--;
1714 argv++;
1715 } else if (push_assumed && !force_assume) {
1716 die("subcommand wasn't specified; 'push' can't be assumed due to unexpected token '%s'",
1717 argv[0]);
1721 parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1722 prefix, argv);
1724 if (pathspec_from_file) {
1725 if (patch_mode)
1726 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1728 if (only_staged)
1729 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--staged");
1731 if (ps.nr)
1732 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1734 parse_pathspec_file(&ps, 0,
1735 PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1736 prefix, pathspec_from_file, pathspec_file_nul);
1737 } else if (pathspec_file_nul) {
1738 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1741 return do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
1742 include_untracked, only_staged);
1745 static int push_stash_unassumed(int argc, const char **argv, const char *prefix)
1747 return push_stash(argc, argv, prefix, 0);
1750 static int save_stash(int argc, const char **argv, const char *prefix)
1752 int keep_index = -1;
1753 int only_staged = 0;
1754 int patch_mode = 0;
1755 int include_untracked = 0;
1756 int quiet = 0;
1757 int ret = 0;
1758 const char *stash_msg = NULL;
1759 struct pathspec ps;
1760 struct strbuf stash_msg_buf = STRBUF_INIT;
1761 struct option options[] = {
1762 OPT_BOOL('k', "keep-index", &keep_index,
1763 N_("keep index")),
1764 OPT_BOOL('S', "staged", &only_staged,
1765 N_("stash staged changes only")),
1766 OPT_BOOL('p', "patch", &patch_mode,
1767 N_("stash in patch mode")),
1768 OPT__QUIET(&quiet, N_("quiet mode")),
1769 OPT_BOOL('u', "include-untracked", &include_untracked,
1770 N_("include untracked files in stash")),
1771 OPT_SET_INT('a', "all", &include_untracked,
1772 N_("include ignore files"), 2),
1773 OPT_STRING('m', "message", &stash_msg, "message",
1774 N_("stash message")),
1775 OPT_END()
1778 argc = parse_options(argc, argv, prefix, options,
1779 git_stash_save_usage,
1780 PARSE_OPT_KEEP_DASHDASH);
1782 if (argc)
1783 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
1785 memset(&ps, 0, sizeof(ps));
1786 ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
1787 patch_mode, include_untracked, only_staged);
1789 strbuf_release(&stash_msg_buf);
1790 return ret;
1793 int cmd_stash(int argc, const char **argv, const char *prefix)
1795 pid_t pid = getpid();
1796 const char *index_file;
1797 struct strvec args = STRVEC_INIT;
1798 parse_opt_subcommand_fn *fn = NULL;
1799 struct option options[] = {
1800 OPT_SUBCOMMAND("apply", &fn, apply_stash),
1801 OPT_SUBCOMMAND("clear", &fn, clear_stash),
1802 OPT_SUBCOMMAND("drop", &fn, drop_stash),
1803 OPT_SUBCOMMAND("pop", &fn, pop_stash),
1804 OPT_SUBCOMMAND("branch", &fn, branch_stash),
1805 OPT_SUBCOMMAND("list", &fn, list_stash),
1806 OPT_SUBCOMMAND("show", &fn, show_stash),
1807 OPT_SUBCOMMAND("store", &fn, store_stash),
1808 OPT_SUBCOMMAND("create", &fn, create_stash),
1809 OPT_SUBCOMMAND("push", &fn, push_stash_unassumed),
1810 OPT_SUBCOMMAND_F("save", &fn, save_stash, PARSE_OPT_NOCOMPLETE),
1811 OPT_END()
1814 git_config(git_stash_config, NULL);
1816 argc = parse_options(argc, argv, prefix, options, git_stash_usage,
1817 PARSE_OPT_SUBCOMMAND_OPTIONAL |
1818 PARSE_OPT_KEEP_UNKNOWN_OPT |
1819 PARSE_OPT_KEEP_DASHDASH);
1821 prepare_repo_settings(the_repository);
1822 the_repository->settings.command_requires_full_index = 0;
1824 index_file = get_index_file();
1825 strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
1826 (uintmax_t)pid);
1828 if (fn)
1829 return !!fn(argc, argv, prefix);
1830 else if (!argc)
1831 return !!push_stash_unassumed(0, NULL, prefix);
1833 /* Assume 'stash push' */
1834 strvec_push(&args, "push");
1835 strvec_pushv(&args, argv);
1836 return !!push_stash(args.nr, args.v, prefix, 1);