Merge branch 'ps/the-index-is-no-more'
[git/gitster.git] / builtin / stash.c
blobbf2834fddd0ce89594060003d16fa05b30bf8325
1 #include "builtin.h"
2 #include "abspath.h"
3 #include "config.h"
4 #include "environment.h"
5 #include "gettext.h"
6 #include "hash.h"
7 #include "hex.h"
8 #include "object-name.h"
9 #include "parse-options.h"
10 #include "refs.h"
11 #include "lockfile.h"
12 #include "cache-tree.h"
13 #include "unpack-trees.h"
14 #include "merge-recursive.h"
15 #include "merge-ort-wrappers.h"
16 #include "strvec.h"
17 #include "run-command.h"
18 #include "dir.h"
19 #include "entry.h"
20 #include "preload-index.h"
21 #include "read-cache.h"
22 #include "rerere.h"
23 #include "revision.h"
24 #include "setup.h"
25 #include "sparse-index.h"
26 #include "log-tree.h"
27 #include "diffcore.h"
28 #include "reflog.h"
29 #include "add-interactive.h"
31 #define INCLUDE_ALL_FILES 2
33 #define BUILTIN_STASH_LIST_USAGE \
34 N_("git stash list [<log-options>]")
35 #define BUILTIN_STASH_SHOW_USAGE \
36 N_("git stash show [-u | --include-untracked | --only-untracked] [<diff-options>] [<stash>]")
37 #define BUILTIN_STASH_DROP_USAGE \
38 N_("git stash drop [-q | --quiet] [<stash>]")
39 #define BUILTIN_STASH_POP_USAGE \
40 N_("git stash pop [--index] [-q | --quiet] [<stash>]")
41 #define BUILTIN_STASH_APPLY_USAGE \
42 N_("git stash apply [--index] [-q | --quiet] [<stash>]")
43 #define BUILTIN_STASH_BRANCH_USAGE \
44 N_("git stash branch <branchname> [<stash>]")
45 #define BUILTIN_STASH_STORE_USAGE \
46 N_("git stash store [(-m | --message) <message>] [-q | --quiet] <commit>")
47 #define BUILTIN_STASH_PUSH_USAGE \
48 N_("git stash [push [-p | --patch] [-S | --staged] [-k | --[no-]keep-index] [-q | --quiet]\n" \
49 " [-u | --include-untracked] [-a | --all] [(-m | --message) <message>]\n" \
50 " [--pathspec-from-file=<file> [--pathspec-file-nul]]\n" \
51 " [--] [<pathspec>...]]")
52 #define BUILTIN_STASH_SAVE_USAGE \
53 N_("git stash save [-p | --patch] [-S | --staged] [-k | --[no-]keep-index] [-q | --quiet]\n" \
54 " [-u | --include-untracked] [-a | --all] [<message>]")
55 #define BUILTIN_STASH_CREATE_USAGE \
56 N_("git stash create [<message>]")
57 #define BUILTIN_STASH_CLEAR_USAGE \
58 "git stash clear"
60 static const char * const git_stash_usage[] = {
61 BUILTIN_STASH_LIST_USAGE,
62 BUILTIN_STASH_SHOW_USAGE,
63 BUILTIN_STASH_DROP_USAGE,
64 BUILTIN_STASH_POP_USAGE,
65 BUILTIN_STASH_APPLY_USAGE,
66 BUILTIN_STASH_BRANCH_USAGE,
67 BUILTIN_STASH_PUSH_USAGE,
68 BUILTIN_STASH_SAVE_USAGE,
69 BUILTIN_STASH_CLEAR_USAGE,
70 BUILTIN_STASH_CREATE_USAGE,
71 BUILTIN_STASH_STORE_USAGE,
72 NULL
75 static const char * const git_stash_list_usage[] = {
76 BUILTIN_STASH_LIST_USAGE,
77 NULL
80 static const char * const git_stash_show_usage[] = {
81 BUILTIN_STASH_SHOW_USAGE,
82 NULL
85 static const char * const git_stash_drop_usage[] = {
86 BUILTIN_STASH_DROP_USAGE,
87 NULL
90 static const char * const git_stash_pop_usage[] = {
91 BUILTIN_STASH_POP_USAGE,
92 NULL
95 static const char * const git_stash_apply_usage[] = {
96 BUILTIN_STASH_APPLY_USAGE,
97 NULL
100 static const char * const git_stash_branch_usage[] = {
101 BUILTIN_STASH_BRANCH_USAGE,
102 NULL
105 static const char * const git_stash_clear_usage[] = {
106 BUILTIN_STASH_CLEAR_USAGE,
107 NULL
110 static const char * const git_stash_store_usage[] = {
111 BUILTIN_STASH_STORE_USAGE,
112 NULL
115 static const char * const git_stash_push_usage[] = {
116 BUILTIN_STASH_PUSH_USAGE,
117 NULL
120 static const char * const git_stash_save_usage[] = {
121 BUILTIN_STASH_SAVE_USAGE,
122 NULL
125 static const char ref_stash[] = "refs/stash";
126 static struct strbuf stash_index_path = STRBUF_INIT;
129 * w_commit is set to the commit containing the working tree
130 * b_commit is set to the base commit
131 * i_commit is set to the commit containing the index tree
132 * u_commit is set to the commit containing the untracked files tree
133 * w_tree is set to the working tree
134 * b_tree is set to the base tree
135 * i_tree is set to the index tree
136 * u_tree is set to the untracked files tree
138 struct stash_info {
139 struct object_id w_commit;
140 struct object_id b_commit;
141 struct object_id i_commit;
142 struct object_id u_commit;
143 struct object_id w_tree;
144 struct object_id b_tree;
145 struct object_id i_tree;
146 struct object_id u_tree;
147 struct strbuf revision;
148 int is_stash_ref;
149 int has_u;
152 #define STASH_INFO_INIT { \
153 .revision = STRBUF_INIT, \
156 static void free_stash_info(struct stash_info *info)
158 strbuf_release(&info->revision);
161 static void assert_stash_like(struct stash_info *info, const char *revision)
163 if (get_oidf(&info->b_commit, "%s^1", revision) ||
164 get_oidf(&info->w_tree, "%s:", revision) ||
165 get_oidf(&info->b_tree, "%s^1:", revision) ||
166 get_oidf(&info->i_tree, "%s^2:", revision))
167 die(_("'%s' is not a stash-like commit"), revision);
170 static int get_stash_info(struct stash_info *info, int argc, const char **argv)
172 int ret;
173 char *end_of_rev;
174 char *expanded_ref;
175 const char *revision;
176 const char *commit = NULL;
177 struct object_id dummy;
178 struct strbuf symbolic = STRBUF_INIT;
180 if (argc > 1) {
181 int i;
182 struct strbuf refs_msg = STRBUF_INIT;
184 for (i = 0; i < argc; i++)
185 strbuf_addf(&refs_msg, " '%s'", argv[i]);
187 fprintf_ln(stderr, _("Too many revisions specified:%s"),
188 refs_msg.buf);
189 strbuf_release(&refs_msg);
191 return -1;
194 if (argc == 1)
195 commit = argv[0];
197 if (!commit) {
198 if (!ref_exists(ref_stash)) {
199 fprintf_ln(stderr, _("No stash entries found."));
200 return -1;
203 strbuf_addf(&info->revision, "%s@{0}", ref_stash);
204 } else if (strspn(commit, "0123456789") == strlen(commit)) {
205 strbuf_addf(&info->revision, "%s@{%s}", ref_stash, commit);
206 } else {
207 strbuf_addstr(&info->revision, commit);
210 revision = info->revision.buf;
212 if (repo_get_oid(the_repository, revision, &info->w_commit))
213 return error(_("%s is not a valid reference"), revision);
215 assert_stash_like(info, revision);
217 info->has_u = !get_oidf(&info->u_tree, "%s^3:", revision);
219 end_of_rev = strchrnul(revision, '@');
220 strbuf_add(&symbolic, revision, end_of_rev - revision);
222 ret = repo_dwim_ref(the_repository, symbolic.buf, symbolic.len,
223 &dummy, &expanded_ref, 0);
224 strbuf_release(&symbolic);
225 switch (ret) {
226 case 0: /* Not found, but valid ref */
227 info->is_stash_ref = 0;
228 break;
229 case 1:
230 info->is_stash_ref = !strcmp(expanded_ref, ref_stash);
231 break;
232 default: /* Invalid or ambiguous */
233 break;
236 free(expanded_ref);
237 return !(ret == 0 || ret == 1);
240 static int do_clear_stash(void)
242 struct object_id obj;
243 if (repo_get_oid(the_repository, ref_stash, &obj))
244 return 0;
246 return delete_ref(NULL, ref_stash, &obj, 0);
249 static int clear_stash(int argc, const char **argv, const char *prefix)
251 struct option options[] = {
252 OPT_END()
255 argc = parse_options(argc, argv, prefix, options,
256 git_stash_clear_usage,
257 PARSE_OPT_STOP_AT_NON_OPTION);
259 if (argc)
260 return error(_("git stash clear with arguments is "
261 "unimplemented"));
263 return do_clear_stash();
266 static int reset_tree(struct object_id *i_tree, int update, int reset)
268 int nr_trees = 1;
269 struct unpack_trees_options opts;
270 struct tree_desc t[MAX_UNPACK_TREES];
271 struct tree *tree;
272 struct lock_file lock_file = LOCK_INIT;
274 repo_read_index_preload(the_repository, NULL, 0);
275 if (refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL))
276 return -1;
278 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
280 memset(&opts, 0, sizeof(opts));
282 tree = parse_tree_indirect(i_tree);
283 if (parse_tree(tree))
284 return -1;
286 init_tree_desc(t, &tree->object.oid, tree->buffer, tree->size);
288 opts.head_idx = 1;
289 opts.src_index = the_repository->index;
290 opts.dst_index = the_repository->index;
291 opts.merge = 1;
292 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
293 opts.update = update;
294 if (update)
295 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
296 opts.fn = oneway_merge;
298 if (unpack_trees(nr_trees, t, &opts))
299 return -1;
301 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
302 return error(_("unable to write new index file"));
304 return 0;
307 static int diff_tree_binary(struct strbuf *out, struct object_id *w_commit)
309 struct child_process cp = CHILD_PROCESS_INIT;
310 const char *w_commit_hex = oid_to_hex(w_commit);
313 * Diff-tree would not be very hard to replace with a native function,
314 * however it should be done together with apply_cached.
316 cp.git_cmd = 1;
317 strvec_pushl(&cp.args, "diff-tree", "--binary", NULL);
318 strvec_pushf(&cp.args, "%s^2^..%s^2", w_commit_hex, w_commit_hex);
320 return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
323 static int apply_cached(struct strbuf *out)
325 struct child_process cp = CHILD_PROCESS_INIT;
328 * Apply currently only reads either from stdin or a file, thus
329 * apply_all_patches would have to be updated to optionally take a
330 * buffer.
332 cp.git_cmd = 1;
333 strvec_pushl(&cp.args, "apply", "--cached", NULL);
334 return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
337 static int reset_head(void)
339 struct child_process cp = CHILD_PROCESS_INIT;
342 * Reset is overall quite simple, however there is no current public
343 * API for resetting.
345 cp.git_cmd = 1;
346 strvec_pushl(&cp.args, "reset", "--quiet", "--refresh", NULL);
348 return run_command(&cp);
351 static int is_path_a_directory(const char *path)
354 * This function differs from abspath.c:is_directory() in that
355 * here we use lstat() instead of stat(); we do not want to
356 * follow symbolic links here.
358 struct stat st;
359 return (!lstat(path, &st) && S_ISDIR(st.st_mode));
362 static void add_diff_to_buf(struct diff_queue_struct *q,
363 struct diff_options *options UNUSED,
364 void *data)
366 int i;
368 for (i = 0; i < q->nr; i++) {
369 if (is_path_a_directory(q->queue[i]->one->path))
370 continue;
372 strbuf_addstr(data, q->queue[i]->one->path);
374 /* NUL-terminate: will be fed to update-index -z */
375 strbuf_addch(data, '\0');
379 static int restore_untracked(struct object_id *u_tree)
381 int res;
382 struct child_process cp = CHILD_PROCESS_INIT;
385 * We need to run restore files from a given index, but without
386 * affecting the current index, so we use GIT_INDEX_FILE with
387 * run_command to fork processes that will not interfere.
389 cp.git_cmd = 1;
390 strvec_push(&cp.args, "read-tree");
391 strvec_push(&cp.args, oid_to_hex(u_tree));
392 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
393 stash_index_path.buf);
394 if (run_command(&cp)) {
395 remove_path(stash_index_path.buf);
396 return -1;
399 child_process_init(&cp);
400 cp.git_cmd = 1;
401 strvec_pushl(&cp.args, "checkout-index", "--all", NULL);
402 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
403 stash_index_path.buf);
405 res = run_command(&cp);
406 remove_path(stash_index_path.buf);
407 return res;
410 static void unstage_changes_unless_new(struct object_id *orig_tree)
413 * When we enter this function, there has been a clean merge of
414 * relevant trees, and the merge logic always stages whatever merges
415 * cleanly. We want to unstage those changes, unless it corresponds
416 * to a file that didn't exist as of orig_tree.
418 * However, if any SKIP_WORKTREE path is modified relative to
419 * orig_tree, then we want to clear the SKIP_WORKTREE bit and write
420 * it to the worktree before unstaging.
423 struct checkout state = CHECKOUT_INIT;
424 struct diff_options diff_opts;
425 struct lock_file lock = LOCK_INIT;
426 int i;
428 /* If any entries have skip_worktree set, we'll have to check 'em out */
429 state.force = 1;
430 state.quiet = 1;
431 state.refresh_cache = 1;
432 state.istate = the_repository->index;
435 * Step 1: get a difference between orig_tree (which corresponding
436 * to the index before a merge was run) and the current index
437 * (reflecting the changes brought in by the merge).
439 repo_diff_setup(the_repository, &diff_opts);
440 diff_opts.flags.recursive = 1;
441 diff_opts.detect_rename = 0;
442 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
443 diff_setup_done(&diff_opts);
445 do_diff_cache(orig_tree, &diff_opts);
446 diffcore_std(&diff_opts);
448 /* Iterate over the paths that changed due to the merge... */
449 for (i = 0; i < diff_queued_diff.nr; i++) {
450 struct diff_filepair *p;
451 struct cache_entry *ce;
452 int pos;
454 /* Look up the path's position in the current index. */
455 p = diff_queued_diff.queue[i];
456 pos = index_name_pos(the_repository->index, p->two->path,
457 strlen(p->two->path));
460 * Step 2: Place changes in the working tree
462 * Stash is about restoring changes *to the working tree*.
463 * So if the merge successfully got a new version of some
464 * path, but left it out of the working tree, then clear the
465 * SKIP_WORKTREE bit and write it to the working tree.
467 if (pos >= 0 && ce_skip_worktree(the_repository->index->cache[pos])) {
468 struct stat st;
470 ce = the_repository->index->cache[pos];
471 if (!lstat(ce->name, &st)) {
472 /* Conflicting path present; relocate it */
473 struct strbuf new_path = STRBUF_INIT;
474 int fd;
476 strbuf_addf(&new_path,
477 "%s.stash.XXXXXX", ce->name);
478 fd = xmkstemp(new_path.buf);
479 close(fd);
480 printf(_("WARNING: Untracked file in way of "
481 "tracked file! Renaming\n "
482 " %s -> %s\n"
483 " to make room.\n"),
484 ce->name, new_path.buf);
485 if (rename(ce->name, new_path.buf))
486 die("Failed to move %s to %s\n",
487 ce->name, new_path.buf);
488 strbuf_release(&new_path);
490 checkout_entry(ce, &state, NULL, NULL);
491 ce->ce_flags &= ~CE_SKIP_WORKTREE;
495 * Step 3: "unstage" changes, as long as they are still tracked
497 if (p->one->oid_valid) {
499 * Path existed in orig_tree; restore index entry
500 * from that tree in order to "unstage" the changes.
502 int option = ADD_CACHE_OK_TO_REPLACE;
503 if (pos < 0)
504 option = ADD_CACHE_OK_TO_ADD;
506 ce = make_cache_entry(the_repository->index,
507 p->one->mode,
508 &p->one->oid,
509 p->one->path,
510 0, 0);
511 add_index_entry(the_repository->index, ce, option);
514 diff_flush(&diff_opts);
517 * Step 4: write the new index to disk
519 repo_hold_locked_index(the_repository, &lock, LOCK_DIE_ON_ERROR);
520 if (write_locked_index(the_repository->index, &lock,
521 COMMIT_LOCK | SKIP_IF_UNCHANGED))
522 die(_("could not write index"));
525 static int do_apply_stash(const char *prefix, struct stash_info *info,
526 int index, int quiet)
528 int clean, ret;
529 int has_index = index;
530 struct merge_options o;
531 struct object_id c_tree;
532 struct object_id index_tree;
533 struct tree *head, *merge, *merge_base;
534 struct lock_file lock = LOCK_INIT;
536 repo_read_index_preload(the_repository, NULL, 0);
537 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
538 NULL, NULL, NULL))
539 return error(_("could not write index"));
541 if (write_index_as_tree(&c_tree, the_repository->index, get_index_file(), 0,
542 NULL))
543 return error(_("cannot apply a stash in the middle of a merge"));
545 if (index) {
546 if (oideq(&info->b_tree, &info->i_tree) ||
547 oideq(&c_tree, &info->i_tree)) {
548 has_index = 0;
549 } else {
550 struct strbuf out = STRBUF_INIT;
552 if (diff_tree_binary(&out, &info->w_commit)) {
553 strbuf_release(&out);
554 return error(_("could not generate diff %s^!."),
555 oid_to_hex(&info->w_commit));
558 ret = apply_cached(&out);
559 strbuf_release(&out);
560 if (ret)
561 return error(_("conflicts in index. "
562 "Try without --index."));
564 discard_index(the_repository->index);
565 repo_read_index(the_repository);
566 if (write_index_as_tree(&index_tree, the_repository->index,
567 get_index_file(), 0, NULL))
568 return error(_("could not save index tree"));
570 reset_head();
571 discard_index(the_repository->index);
572 repo_read_index(the_repository);
576 init_merge_options(&o, the_repository);
578 o.branch1 = "Updated upstream";
579 o.branch2 = "Stashed changes";
580 o.ancestor = "Stash base";
582 if (oideq(&info->b_tree, &c_tree))
583 o.branch1 = "Version stash was based on";
585 if (quiet)
586 o.verbosity = 0;
588 if (o.verbosity >= 3)
589 printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
591 head = lookup_tree(o.repo, &c_tree);
592 merge = lookup_tree(o.repo, &info->w_tree);
593 merge_base = lookup_tree(o.repo, &info->b_tree);
595 repo_hold_locked_index(o.repo, &lock, LOCK_DIE_ON_ERROR);
596 clean = merge_ort_nonrecursive(&o, head, merge, merge_base);
599 * If 'clean' >= 0, reverse the value for 'ret' so 'ret' is 0 when the
600 * merge was clean, and nonzero if the merge was unclean or encountered
601 * an error.
603 ret = clean >= 0 ? !clean : clean;
605 if (ret < 0)
606 rollback_lock_file(&lock);
607 else if (write_locked_index(o.repo->index, &lock,
608 COMMIT_LOCK | SKIP_IF_UNCHANGED))
609 ret = error(_("could not write index"));
611 if (ret) {
612 repo_rerere(the_repository, 0);
614 if (index)
615 fprintf_ln(stderr, _("Index was not unstashed."));
617 goto restore_untracked;
620 if (has_index) {
621 if (reset_tree(&index_tree, 0, 0))
622 ret = -1;
623 } else {
624 unstage_changes_unless_new(&c_tree);
627 restore_untracked:
628 if (info->has_u && restore_untracked(&info->u_tree))
629 ret = error(_("could not restore untracked files from stash"));
631 if (!quiet) {
632 struct child_process cp = CHILD_PROCESS_INIT;
635 * Status is quite simple and could be replaced with calls to
636 * wt_status in the future, but it adds complexities which may
637 * require more tests.
639 cp.git_cmd = 1;
640 cp.dir = prefix;
641 strvec_pushf(&cp.env, GIT_WORK_TREE_ENVIRONMENT"=%s",
642 absolute_path(get_git_work_tree()));
643 strvec_pushf(&cp.env, GIT_DIR_ENVIRONMENT"=%s",
644 absolute_path(get_git_dir()));
645 strvec_push(&cp.args, "status");
646 run_command(&cp);
649 return ret;
652 static int apply_stash(int argc, const char **argv, const char *prefix)
654 int ret = -1;
655 int quiet = 0;
656 int index = 0;
657 struct stash_info info = STASH_INFO_INIT;
658 struct option options[] = {
659 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
660 OPT_BOOL(0, "index", &index,
661 N_("attempt to recreate the index")),
662 OPT_END()
665 argc = parse_options(argc, argv, prefix, options,
666 git_stash_apply_usage, 0);
668 if (get_stash_info(&info, argc, argv))
669 goto cleanup;
671 ret = do_apply_stash(prefix, &info, index, quiet);
672 cleanup:
673 free_stash_info(&info);
674 return ret;
677 static int reject_reflog_ent(struct object_id *ooid UNUSED,
678 struct object_id *noid UNUSED,
679 const char *email UNUSED,
680 timestamp_t timestamp UNUSED,
681 int tz UNUSED, const char *message UNUSED,
682 void *cb_data UNUSED)
684 return 1;
687 static int reflog_is_empty(const char *refname)
689 return !for_each_reflog_ent(refname, reject_reflog_ent, NULL);
692 static int do_drop_stash(struct stash_info *info, int quiet)
694 if (!reflog_delete(info->revision.buf,
695 EXPIRE_REFLOGS_REWRITE | EXPIRE_REFLOGS_UPDATE_REF,
696 0)) {
697 if (!quiet)
698 printf_ln(_("Dropped %s (%s)"), info->revision.buf,
699 oid_to_hex(&info->w_commit));
700 } else {
701 return error(_("%s: Could not drop stash entry"),
702 info->revision.buf);
705 if (reflog_is_empty(ref_stash))
706 do_clear_stash();
708 return 0;
711 static int get_stash_info_assert(struct stash_info *info, int argc,
712 const char **argv)
714 int ret = get_stash_info(info, argc, argv);
716 if (ret < 0)
717 return ret;
719 if (!info->is_stash_ref)
720 return error(_("'%s' is not a stash reference"), info->revision.buf);
722 return 0;
725 static int drop_stash(int argc, const char **argv, const char *prefix)
727 int ret = -1;
728 int quiet = 0;
729 struct stash_info info = STASH_INFO_INIT;
730 struct option options[] = {
731 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
732 OPT_END()
735 argc = parse_options(argc, argv, prefix, options,
736 git_stash_drop_usage, 0);
738 if (get_stash_info_assert(&info, argc, argv))
739 goto cleanup;
741 ret = do_drop_stash(&info, quiet);
742 cleanup:
743 free_stash_info(&info);
744 return ret;
747 static int pop_stash(int argc, const char **argv, const char *prefix)
749 int ret = -1;
750 int index = 0;
751 int quiet = 0;
752 struct stash_info info = STASH_INFO_INIT;
753 struct option options[] = {
754 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
755 OPT_BOOL(0, "index", &index,
756 N_("attempt to recreate the index")),
757 OPT_END()
760 argc = parse_options(argc, argv, prefix, options,
761 git_stash_pop_usage, 0);
763 if (get_stash_info_assert(&info, argc, argv))
764 goto cleanup;
766 if ((ret = do_apply_stash(prefix, &info, index, quiet)))
767 printf_ln(_("The stash entry is kept in case "
768 "you need it again."));
769 else
770 ret = do_drop_stash(&info, quiet);
772 cleanup:
773 free_stash_info(&info);
774 return ret;
777 static int branch_stash(int argc, const char **argv, const char *prefix)
779 int ret = -1;
780 const char *branch = NULL;
781 struct stash_info info = STASH_INFO_INIT;
782 struct child_process cp = CHILD_PROCESS_INIT;
783 struct option options[] = {
784 OPT_END()
787 argc = parse_options(argc, argv, prefix, options,
788 git_stash_branch_usage, 0);
790 if (!argc) {
791 fprintf_ln(stderr, _("No branch name specified"));
792 return -1;
795 branch = argv[0];
797 if (get_stash_info(&info, argc - 1, argv + 1))
798 goto cleanup;
800 cp.git_cmd = 1;
801 strvec_pushl(&cp.args, "checkout", "-b", NULL);
802 strvec_push(&cp.args, branch);
803 strvec_push(&cp.args, oid_to_hex(&info.b_commit));
804 ret = run_command(&cp);
805 if (!ret)
806 ret = do_apply_stash(prefix, &info, 1, 0);
807 if (!ret && info.is_stash_ref)
808 ret = do_drop_stash(&info, 0);
810 cleanup:
811 free_stash_info(&info);
812 return ret;
815 static int list_stash(int argc, const char **argv, const char *prefix)
817 struct child_process cp = CHILD_PROCESS_INIT;
818 struct option options[] = {
819 OPT_END()
822 argc = parse_options(argc, argv, prefix, options,
823 git_stash_list_usage,
824 PARSE_OPT_KEEP_UNKNOWN_OPT);
826 if (!ref_exists(ref_stash))
827 return 0;
829 cp.git_cmd = 1;
830 strvec_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
831 "--first-parent", NULL);
832 strvec_pushv(&cp.args, argv);
833 strvec_push(&cp.args, ref_stash);
834 strvec_push(&cp.args, "--");
835 return run_command(&cp);
838 static int show_stat = 1;
839 static int show_patch;
840 static int show_include_untracked;
842 static int git_stash_config(const char *var, const char *value,
843 const struct config_context *ctx, void *cb)
845 if (!strcmp(var, "stash.showstat")) {
846 show_stat = git_config_bool(var, value);
847 return 0;
849 if (!strcmp(var, "stash.showpatch")) {
850 show_patch = git_config_bool(var, value);
851 return 0;
853 if (!strcmp(var, "stash.showincludeuntracked")) {
854 show_include_untracked = git_config_bool(var, value);
855 return 0;
857 return git_diff_basic_config(var, value, ctx, cb);
860 static void diff_include_untracked(const struct stash_info *info, struct diff_options *diff_opt)
862 const struct object_id *oid[] = { &info->w_commit, &info->u_tree };
863 struct tree *tree[ARRAY_SIZE(oid)];
864 struct tree_desc tree_desc[ARRAY_SIZE(oid)];
865 struct unpack_trees_options unpack_tree_opt = { 0 };
866 int i;
868 for (i = 0; i < ARRAY_SIZE(oid); i++) {
869 tree[i] = parse_tree_indirect(oid[i]);
870 if (parse_tree(tree[i]) < 0)
871 die(_("failed to parse tree"));
872 init_tree_desc(&tree_desc[i], &tree[i]->object.oid,
873 tree[i]->buffer, tree[i]->size);
876 unpack_tree_opt.head_idx = -1;
877 unpack_tree_opt.src_index = the_repository->index;
878 unpack_tree_opt.dst_index = the_repository->index;
879 unpack_tree_opt.merge = 1;
880 unpack_tree_opt.fn = stash_worktree_untracked_merge;
882 if (unpack_trees(ARRAY_SIZE(tree_desc), tree_desc, &unpack_tree_opt))
883 die(_("failed to unpack trees"));
885 do_diff_cache(&info->b_commit, diff_opt);
888 static int show_stash(int argc, const char **argv, const char *prefix)
890 int i;
891 int ret = -1;
892 struct stash_info info = STASH_INFO_INIT;
893 struct rev_info rev;
894 struct strvec stash_args = STRVEC_INIT;
895 struct strvec revision_args = STRVEC_INIT;
896 enum {
897 UNTRACKED_NONE,
898 UNTRACKED_INCLUDE,
899 UNTRACKED_ONLY
900 } show_untracked = show_include_untracked ? UNTRACKED_INCLUDE : UNTRACKED_NONE;
901 struct option options[] = {
902 OPT_SET_INT('u', "include-untracked", &show_untracked,
903 N_("include untracked files in the stash"),
904 UNTRACKED_INCLUDE),
905 OPT_SET_INT_F(0, "only-untracked", &show_untracked,
906 N_("only show untracked files in the stash"),
907 UNTRACKED_ONLY, PARSE_OPT_NONEG),
908 OPT_END()
910 int do_usage = 0;
912 init_diff_ui_defaults();
913 git_config(git_diff_ui_config, NULL);
914 repo_init_revisions(the_repository, &rev, prefix);
916 argc = parse_options(argc, argv, prefix, options, git_stash_show_usage,
917 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
918 PARSE_OPT_KEEP_DASHDASH);
920 strvec_push(&revision_args, argv[0]);
921 for (i = 1; i < argc; i++) {
922 if (argv[i][0] != '-')
923 strvec_push(&stash_args, argv[i]);
924 else
925 strvec_push(&revision_args, argv[i]);
928 if (get_stash_info(&info, stash_args.nr, stash_args.v))
929 goto cleanup;
932 * The config settings are applied only if there are not passed
933 * any options.
935 if (revision_args.nr == 1) {
936 if (show_stat)
937 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
939 if (show_patch)
940 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
942 if (!show_stat && !show_patch) {
943 ret = 0;
944 goto cleanup;
948 argc = setup_revisions(revision_args.nr, revision_args.v, &rev, NULL);
949 if (argc > 1)
950 goto usage;
951 if (!rev.diffopt.output_format) {
952 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
953 diff_setup_done(&rev.diffopt);
956 rev.diffopt.flags.recursive = 1;
957 setup_diff_pager(&rev.diffopt);
958 switch (show_untracked) {
959 case UNTRACKED_NONE:
960 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
961 break;
962 case UNTRACKED_ONLY:
963 if (info.has_u)
964 diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
965 break;
966 case UNTRACKED_INCLUDE:
967 if (info.has_u)
968 diff_include_untracked(&info, &rev.diffopt);
969 else
970 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
971 break;
973 log_tree_diff_flush(&rev);
975 ret = diff_result_code(&rev.diffopt);
976 cleanup:
977 strvec_clear(&stash_args);
978 free_stash_info(&info);
979 release_revisions(&rev);
980 if (do_usage)
981 usage_with_options(git_stash_show_usage, options);
982 return ret;
983 usage:
984 do_usage = 1;
985 goto cleanup;
988 static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
989 int quiet)
991 struct stash_info info;
992 char revision[GIT_MAX_HEXSZ];
994 oid_to_hex_r(revision, w_commit);
995 assert_stash_like(&info, revision);
997 if (!stash_msg)
998 stash_msg = "Created via \"git stash store\".";
1000 if (update_ref(stash_msg, ref_stash, w_commit, NULL,
1001 REF_FORCE_CREATE_REFLOG,
1002 quiet ? UPDATE_REFS_QUIET_ON_ERR :
1003 UPDATE_REFS_MSG_ON_ERR)) {
1004 if (!quiet) {
1005 fprintf_ln(stderr, _("Cannot update %s with %s"),
1006 ref_stash, oid_to_hex(w_commit));
1008 return -1;
1011 return 0;
1014 static int store_stash(int argc, const char **argv, const char *prefix)
1016 int quiet = 0;
1017 const char *stash_msg = NULL;
1018 struct object_id obj;
1019 struct object_context dummy;
1020 struct option options[] = {
1021 OPT__QUIET(&quiet, N_("be quiet")),
1022 OPT_STRING('m', "message", &stash_msg, "message",
1023 N_("stash message")),
1024 OPT_END()
1027 argc = parse_options(argc, argv, prefix, options,
1028 git_stash_store_usage,
1029 PARSE_OPT_KEEP_UNKNOWN_OPT);
1031 if (argc != 1) {
1032 if (!quiet)
1033 fprintf_ln(stderr, _("\"git stash store\" requires one "
1034 "<commit> argument"));
1035 return -1;
1038 if (get_oid_with_context(the_repository,
1039 argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
1040 &dummy)) {
1041 if (!quiet)
1042 fprintf_ln(stderr, _("Cannot update %s with %s"),
1043 ref_stash, argv[0]);
1044 return -1;
1047 return do_store_stash(&obj, stash_msg, quiet);
1050 static void add_pathspecs(struct strvec *args,
1051 const struct pathspec *ps) {
1052 int i;
1054 for (i = 0; i < ps->nr; i++)
1055 strvec_push(args, ps->items[i].original);
1059 * `untracked_files` will be filled with the names of untracked files.
1060 * The return value is:
1062 * = 0 if there are not any untracked files
1063 * > 0 if there are untracked files
1065 static int get_untracked_files(const struct pathspec *ps, int include_untracked,
1066 struct strbuf *untracked_files)
1068 int i;
1069 int found = 0;
1070 struct dir_struct dir = DIR_INIT;
1072 if (include_untracked != INCLUDE_ALL_FILES)
1073 setup_standard_excludes(&dir);
1075 fill_directory(&dir, the_repository->index, ps);
1076 for (i = 0; i < dir.nr; i++) {
1077 struct dir_entry *ent = dir.entries[i];
1078 found++;
1079 strbuf_addstr(untracked_files, ent->name);
1080 /* NUL-terminate: will be fed to update-index -z */
1081 strbuf_addch(untracked_files, '\0');
1084 dir_clear(&dir);
1085 return found;
1089 * The return value of `check_changes_tracked_files()` can be:
1091 * < 0 if there was an error
1092 * = 0 if there are no changes.
1093 * > 0 if there are changes.
1095 static int check_changes_tracked_files(const struct pathspec *ps)
1097 struct rev_info rev;
1098 struct object_id dummy;
1099 int ret = 0;
1101 /* No initial commit. */
1102 if (repo_get_oid(the_repository, "HEAD", &dummy))
1103 return -1;
1105 if (repo_read_index(the_repository) < 0)
1106 return -1;
1108 repo_init_revisions(the_repository, &rev, NULL);
1109 copy_pathspec(&rev.prune_data, ps);
1111 rev.diffopt.flags.quick = 1;
1112 rev.diffopt.flags.ignore_submodules = 1;
1113 rev.abbrev = 0;
1115 add_head_to_pending(&rev);
1116 diff_setup_done(&rev.diffopt);
1118 run_diff_index(&rev, DIFF_INDEX_CACHED);
1119 if (diff_result_code(&rev.diffopt)) {
1120 ret = 1;
1121 goto done;
1124 run_diff_files(&rev, 0);
1125 if (diff_result_code(&rev.diffopt)) {
1126 ret = 1;
1127 goto done;
1130 done:
1131 release_revisions(&rev);
1132 return ret;
1136 * The function will fill `untracked_files` with the names of untracked files
1137 * It will return 1 if there were any changes and 0 if there were not.
1139 static int check_changes(const struct pathspec *ps, int include_untracked,
1140 struct strbuf *untracked_files)
1142 int ret = 0;
1143 if (check_changes_tracked_files(ps))
1144 ret = 1;
1146 if (include_untracked && get_untracked_files(ps, include_untracked,
1147 untracked_files))
1148 ret = 1;
1150 return ret;
1153 static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
1154 struct strbuf files)
1156 int ret = 0;
1157 struct strbuf untracked_msg = STRBUF_INIT;
1158 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1159 struct index_state istate = INDEX_STATE_INIT(the_repository);
1161 cp_upd_index.git_cmd = 1;
1162 strvec_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
1163 "--remove", "--stdin", NULL);
1164 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1165 stash_index_path.buf);
1167 strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
1168 if (pipe_command(&cp_upd_index, files.buf, files.len, NULL, 0,
1169 NULL, 0)) {
1170 ret = -1;
1171 goto done;
1174 if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
1175 NULL)) {
1176 ret = -1;
1177 goto done;
1180 if (commit_tree(untracked_msg.buf, untracked_msg.len,
1181 &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
1182 ret = -1;
1183 goto done;
1186 done:
1187 release_index(&istate);
1188 strbuf_release(&untracked_msg);
1189 remove_path(stash_index_path.buf);
1190 return ret;
1193 static int stash_staged(struct stash_info *info, struct strbuf *out_patch,
1194 int quiet)
1196 int ret = 0;
1197 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1198 struct index_state istate = INDEX_STATE_INIT(the_repository);
1200 if (write_index_as_tree(&info->w_tree, &istate, the_repository->index_file,
1201 0, NULL)) {
1202 ret = -1;
1203 goto done;
1206 cp_diff_tree.git_cmd = 1;
1207 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "--binary",
1208 "-U1", "HEAD", oid_to_hex(&info->w_tree), "--", NULL);
1209 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1210 ret = -1;
1211 goto done;
1214 if (!out_patch->len) {
1215 if (!quiet)
1216 fprintf_ln(stderr, _("No staged changes"));
1217 ret = 1;
1220 done:
1221 release_index(&istate);
1222 return ret;
1225 static int stash_patch(struct stash_info *info, const struct pathspec *ps,
1226 struct strbuf *out_patch, int quiet)
1228 int ret = 0;
1229 struct child_process cp_read_tree = CHILD_PROCESS_INIT;
1230 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1231 struct index_state istate = INDEX_STATE_INIT(the_repository);
1232 char *old_index_env = NULL, *old_repo_index_file;
1234 remove_path(stash_index_path.buf);
1236 cp_read_tree.git_cmd = 1;
1237 strvec_pushl(&cp_read_tree.args, "read-tree", "HEAD", NULL);
1238 strvec_pushf(&cp_read_tree.env, "GIT_INDEX_FILE=%s",
1239 stash_index_path.buf);
1240 if (run_command(&cp_read_tree)) {
1241 ret = -1;
1242 goto done;
1245 /* Find out what the user wants. */
1246 old_repo_index_file = the_repository->index_file;
1247 the_repository->index_file = stash_index_path.buf;
1248 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
1249 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
1251 ret = !!run_add_p(the_repository, ADD_P_STASH, NULL, ps);
1253 the_repository->index_file = old_repo_index_file;
1254 if (old_index_env && *old_index_env)
1255 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
1256 else
1257 unsetenv(INDEX_ENVIRONMENT);
1258 FREE_AND_NULL(old_index_env);
1260 /* State of the working tree. */
1261 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1262 NULL)) {
1263 ret = -1;
1264 goto done;
1267 cp_diff_tree.git_cmd = 1;
1268 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1269 oid_to_hex(&info->w_tree), "--", NULL);
1270 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1271 ret = -1;
1272 goto done;
1275 if (!out_patch->len) {
1276 if (!quiet)
1277 fprintf_ln(stderr, _("No changes selected"));
1278 ret = 1;
1281 done:
1282 release_index(&istate);
1283 remove_path(stash_index_path.buf);
1284 return ret;
1287 static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
1289 int ret = 0;
1290 struct rev_info rev;
1291 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1292 struct strbuf diff_output = STRBUF_INIT;
1293 struct index_state istate = INDEX_STATE_INIT(the_repository);
1295 repo_init_revisions(the_repository, &rev, NULL);
1296 copy_pathspec(&rev.prune_data, ps);
1298 set_alternate_index_output(stash_index_path.buf);
1299 if (reset_tree(&info->i_tree, 0, 0)) {
1300 ret = -1;
1301 goto done;
1303 set_alternate_index_output(NULL);
1305 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1306 rev.diffopt.format_callback = add_diff_to_buf;
1307 rev.diffopt.format_callback_data = &diff_output;
1309 if (repo_read_index_preload(the_repository, &rev.diffopt.pathspec, 0) < 0) {
1310 ret = -1;
1311 goto done;
1314 add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1315 "");
1316 run_diff_index(&rev, 0);
1318 cp_upd_index.git_cmd = 1;
1319 strvec_pushl(&cp_upd_index.args, "update-index",
1320 "--ignore-skip-worktree-entries",
1321 "-z", "--add", "--remove", "--stdin", NULL);
1322 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1323 stash_index_path.buf);
1325 if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1326 NULL, 0, NULL, 0)) {
1327 ret = -1;
1328 goto done;
1331 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1332 NULL)) {
1333 ret = -1;
1334 goto done;
1337 done:
1338 release_index(&istate);
1339 release_revisions(&rev);
1340 strbuf_release(&diff_output);
1341 remove_path(stash_index_path.buf);
1342 return ret;
1345 static int do_create_stash(const struct pathspec *ps, struct strbuf *stash_msg_buf,
1346 int include_untracked, int patch_mode, int only_staged,
1347 struct stash_info *info, struct strbuf *patch,
1348 int quiet)
1350 int ret = 0;
1351 int flags = 0;
1352 int untracked_commit_option = 0;
1353 const char *head_short_sha1 = NULL;
1354 const char *branch_ref = NULL;
1355 const char *branch_name = "(no branch)";
1356 struct commit *head_commit = NULL;
1357 struct commit_list *parents = NULL;
1358 struct strbuf msg = STRBUF_INIT;
1359 struct strbuf commit_tree_label = STRBUF_INIT;
1360 struct strbuf untracked_files = STRBUF_INIT;
1362 prepare_fallback_ident("git stash", "git@stash");
1364 repo_read_index_preload(the_repository, NULL, 0);
1365 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1366 NULL, NULL, NULL) < 0) {
1367 ret = error(_("could not write index"));
1368 goto done;
1371 if (repo_get_oid(the_repository, "HEAD", &info->b_commit)) {
1372 if (!quiet)
1373 fprintf_ln(stderr, _("You do not have "
1374 "the initial commit yet"));
1375 ret = -1;
1376 goto done;
1377 } else {
1378 head_commit = lookup_commit(the_repository, &info->b_commit);
1381 if (!check_changes(ps, include_untracked, &untracked_files)) {
1382 ret = 1;
1383 goto done;
1386 branch_ref = resolve_ref_unsafe("HEAD", 0, NULL, &flags);
1387 if (flags & REF_ISSYMREF)
1388 skip_prefix(branch_ref, "refs/heads/", &branch_name);
1389 head_short_sha1 = repo_find_unique_abbrev(the_repository,
1390 &head_commit->object.oid,
1391 DEFAULT_ABBREV);
1392 strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1393 pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1395 strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1396 commit_list_insert(head_commit, &parents);
1397 if (write_index_as_tree(&info->i_tree, the_repository->index, get_index_file(), 0,
1398 NULL) ||
1399 commit_tree(commit_tree_label.buf, commit_tree_label.len,
1400 &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1401 if (!quiet)
1402 fprintf_ln(stderr, _("Cannot save the current "
1403 "index state"));
1404 ret = -1;
1405 goto done;
1408 if (include_untracked) {
1409 if (save_untracked_files(info, &msg, untracked_files)) {
1410 if (!quiet)
1411 fprintf_ln(stderr, _("Cannot save "
1412 "the untracked files"));
1413 ret = -1;
1414 goto done;
1416 untracked_commit_option = 1;
1418 if (patch_mode) {
1419 ret = stash_patch(info, ps, patch, quiet);
1420 if (ret < 0) {
1421 if (!quiet)
1422 fprintf_ln(stderr, _("Cannot save the current "
1423 "worktree state"));
1424 goto done;
1425 } else if (ret > 0) {
1426 goto done;
1428 } else if (only_staged) {
1429 ret = stash_staged(info, patch, quiet);
1430 if (ret < 0) {
1431 if (!quiet)
1432 fprintf_ln(stderr, _("Cannot save the current "
1433 "staged state"));
1434 goto done;
1435 } else if (ret > 0) {
1436 goto done;
1438 } else {
1439 if (stash_working_tree(info, ps)) {
1440 if (!quiet)
1441 fprintf_ln(stderr, _("Cannot save the current "
1442 "worktree state"));
1443 ret = -1;
1444 goto done;
1448 if (!stash_msg_buf->len)
1449 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1450 else
1451 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1454 * `parents` will be empty after calling `commit_tree()`, so there is
1455 * no need to call `free_commit_list()`
1457 parents = NULL;
1458 if (untracked_commit_option)
1459 commit_list_insert(lookup_commit(the_repository,
1460 &info->u_commit),
1461 &parents);
1462 commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1463 &parents);
1464 commit_list_insert(head_commit, &parents);
1466 if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1467 parents, &info->w_commit, NULL, NULL)) {
1468 if (!quiet)
1469 fprintf_ln(stderr, _("Cannot record "
1470 "working tree state"));
1471 ret = -1;
1472 goto done;
1475 done:
1476 strbuf_release(&commit_tree_label);
1477 strbuf_release(&msg);
1478 strbuf_release(&untracked_files);
1479 return ret;
1482 static int create_stash(int argc, const char **argv, const char *prefix UNUSED)
1484 int ret;
1485 struct strbuf stash_msg_buf = STRBUF_INIT;
1486 struct stash_info info = STASH_INFO_INIT;
1487 struct pathspec ps;
1489 /* Starting with argv[1], since argv[0] is "create" */
1490 strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
1492 memset(&ps, 0, sizeof(ps));
1493 if (!check_changes_tracked_files(&ps))
1494 return 0;
1496 ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, 0, &info,
1497 NULL, 0);
1498 if (!ret)
1499 printf_ln("%s", oid_to_hex(&info.w_commit));
1501 free_stash_info(&info);
1502 strbuf_release(&stash_msg_buf);
1503 return ret;
1506 static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int quiet,
1507 int keep_index, int patch_mode, int include_untracked, int only_staged)
1509 int ret = 0;
1510 struct stash_info info = STASH_INFO_INIT;
1511 struct strbuf patch = STRBUF_INIT;
1512 struct strbuf stash_msg_buf = STRBUF_INIT;
1513 struct strbuf untracked_files = STRBUF_INIT;
1515 if (patch_mode && keep_index == -1)
1516 keep_index = 1;
1518 if (patch_mode && include_untracked) {
1519 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1520 " or --all at the same time"));
1521 ret = -1;
1522 goto done;
1525 /* --patch overrides --staged */
1526 if (patch_mode)
1527 only_staged = 0;
1529 if (only_staged && include_untracked) {
1530 fprintf_ln(stderr, _("Can't use --staged and --include-untracked"
1531 " or --all at the same time"));
1532 ret = -1;
1533 goto done;
1536 repo_read_index_preload(the_repository, NULL, 0);
1537 if (!include_untracked && ps->nr) {
1538 int i;
1539 char *ps_matched = xcalloc(ps->nr, 1);
1541 /* TODO: audit for interaction with sparse-index. */
1542 ensure_full_index(the_repository->index);
1543 for (i = 0; i < the_repository->index->cache_nr; i++)
1544 ce_path_match(the_repository->index, the_repository->index->cache[i], ps,
1545 ps_matched);
1547 if (report_path_error(ps_matched, ps)) {
1548 fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1549 ret = -1;
1550 free(ps_matched);
1551 goto done;
1553 free(ps_matched);
1556 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1557 NULL, NULL, NULL)) {
1558 ret = error(_("could not write index"));
1559 goto done;
1562 if (!check_changes(ps, include_untracked, &untracked_files)) {
1563 if (!quiet)
1564 printf_ln(_("No local changes to save"));
1565 goto done;
1568 if (!reflog_exists(ref_stash) && do_clear_stash()) {
1569 ret = -1;
1570 if (!quiet)
1571 fprintf_ln(stderr, _("Cannot initialize stash"));
1572 goto done;
1575 if (stash_msg)
1576 strbuf_addstr(&stash_msg_buf, stash_msg);
1577 if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode, only_staged,
1578 &info, &patch, quiet)) {
1579 ret = -1;
1580 goto done;
1583 if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1584 ret = -1;
1585 if (!quiet)
1586 fprintf_ln(stderr, _("Cannot save the current status"));
1587 goto done;
1590 if (!quiet)
1591 printf_ln(_("Saved working directory and index state %s"),
1592 stash_msg_buf.buf);
1594 if (!(patch_mode || only_staged)) {
1595 if (include_untracked && !ps->nr) {
1596 struct child_process cp = CHILD_PROCESS_INIT;
1598 cp.git_cmd = 1;
1599 if (startup_info->original_cwd) {
1600 cp.dir = startup_info->original_cwd;
1601 strvec_pushf(&cp.env, "%s=%s",
1602 GIT_WORK_TREE_ENVIRONMENT,
1603 the_repository->worktree);
1605 strvec_pushl(&cp.args, "clean", "--force",
1606 "--quiet", "-d", ":/", NULL);
1607 if (include_untracked == INCLUDE_ALL_FILES)
1608 strvec_push(&cp.args, "-x");
1609 if (run_command(&cp)) {
1610 ret = -1;
1611 goto done;
1614 discard_index(the_repository->index);
1615 if (ps->nr) {
1616 struct child_process cp_add = CHILD_PROCESS_INIT;
1617 struct child_process cp_diff = CHILD_PROCESS_INIT;
1618 struct child_process cp_apply = CHILD_PROCESS_INIT;
1619 struct strbuf out = STRBUF_INIT;
1621 cp_add.git_cmd = 1;
1622 strvec_push(&cp_add.args, "add");
1623 if (!include_untracked)
1624 strvec_push(&cp_add.args, "-u");
1625 if (include_untracked == INCLUDE_ALL_FILES)
1626 strvec_push(&cp_add.args, "--force");
1627 strvec_push(&cp_add.args, "--");
1628 add_pathspecs(&cp_add.args, ps);
1629 if (run_command(&cp_add)) {
1630 ret = -1;
1631 goto done;
1634 cp_diff.git_cmd = 1;
1635 strvec_pushl(&cp_diff.args, "diff-index", "-p",
1636 "--cached", "--binary", "HEAD", "--",
1637 NULL);
1638 add_pathspecs(&cp_diff.args, ps);
1639 if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1640 ret = -1;
1641 goto done;
1644 cp_apply.git_cmd = 1;
1645 strvec_pushl(&cp_apply.args, "apply", "--index",
1646 "-R", NULL);
1647 if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1648 NULL, 0)) {
1649 ret = -1;
1650 goto done;
1652 } else {
1653 struct child_process cp = CHILD_PROCESS_INIT;
1654 cp.git_cmd = 1;
1655 /* BUG: this nukes untracked files in the way */
1656 strvec_pushl(&cp.args, "reset", "--hard", "-q",
1657 "--no-recurse-submodules", NULL);
1658 if (run_command(&cp)) {
1659 ret = -1;
1660 goto done;
1664 if (keep_index == 1 && !is_null_oid(&info.i_tree)) {
1665 struct child_process cp = CHILD_PROCESS_INIT;
1667 cp.git_cmd = 1;
1668 strvec_pushl(&cp.args, "checkout", "--no-overlay",
1669 oid_to_hex(&info.i_tree), "--", NULL);
1670 if (!ps->nr)
1671 strvec_push(&cp.args, ":/");
1672 else
1673 add_pathspecs(&cp.args, ps);
1674 if (run_command(&cp)) {
1675 ret = -1;
1676 goto done;
1679 goto done;
1680 } else {
1681 struct child_process cp = CHILD_PROCESS_INIT;
1683 cp.git_cmd = 1;
1684 strvec_pushl(&cp.args, "apply", "-R", NULL);
1686 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1687 if (!quiet)
1688 fprintf_ln(stderr, _("Cannot remove "
1689 "worktree changes"));
1690 ret = -1;
1691 goto done;
1694 if (keep_index < 1) {
1695 struct child_process cp = CHILD_PROCESS_INIT;
1697 cp.git_cmd = 1;
1698 strvec_pushl(&cp.args, "reset", "-q", "--refresh", "--",
1699 NULL);
1700 add_pathspecs(&cp.args, ps);
1701 if (run_command(&cp)) {
1702 ret = -1;
1703 goto done;
1706 goto done;
1709 done:
1710 strbuf_release(&patch);
1711 free_stash_info(&info);
1712 strbuf_release(&stash_msg_buf);
1713 strbuf_release(&untracked_files);
1714 return ret;
1717 static int push_stash(int argc, const char **argv, const char *prefix,
1718 int push_assumed)
1720 int force_assume = 0;
1721 int keep_index = -1;
1722 int only_staged = 0;
1723 int patch_mode = 0;
1724 int include_untracked = 0;
1725 int quiet = 0;
1726 int pathspec_file_nul = 0;
1727 const char *stash_msg = NULL;
1728 const char *pathspec_from_file = NULL;
1729 struct pathspec ps;
1730 struct option options[] = {
1731 OPT_BOOL('k', "keep-index", &keep_index,
1732 N_("keep index")),
1733 OPT_BOOL('S', "staged", &only_staged,
1734 N_("stash staged changes only")),
1735 OPT_BOOL('p', "patch", &patch_mode,
1736 N_("stash in patch mode")),
1737 OPT__QUIET(&quiet, N_("quiet mode")),
1738 OPT_BOOL('u', "include-untracked", &include_untracked,
1739 N_("include untracked files in stash")),
1740 OPT_SET_INT('a', "all", &include_untracked,
1741 N_("include ignore files"), 2),
1742 OPT_STRING('m', "message", &stash_msg, N_("message"),
1743 N_("stash message")),
1744 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1745 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1746 OPT_END()
1748 int ret;
1750 if (argc) {
1751 force_assume = !strcmp(argv[0], "-p");
1752 argc = parse_options(argc, argv, prefix, options,
1753 push_assumed ? git_stash_usage :
1754 git_stash_push_usage,
1755 PARSE_OPT_KEEP_DASHDASH);
1758 if (argc) {
1759 if (!strcmp(argv[0], "--")) {
1760 argc--;
1761 argv++;
1762 } else if (push_assumed && !force_assume) {
1763 die("subcommand wasn't specified; 'push' can't be assumed due to unexpected token '%s'",
1764 argv[0]);
1768 parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1769 prefix, argv);
1771 if (pathspec_from_file) {
1772 if (patch_mode)
1773 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1775 if (only_staged)
1776 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--staged");
1778 if (ps.nr)
1779 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1781 parse_pathspec_file(&ps, 0,
1782 PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1783 prefix, pathspec_from_file, pathspec_file_nul);
1784 } else if (pathspec_file_nul) {
1785 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1788 ret = do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
1789 include_untracked, only_staged);
1790 clear_pathspec(&ps);
1791 return ret;
1794 static int push_stash_unassumed(int argc, const char **argv, const char *prefix)
1796 return push_stash(argc, argv, prefix, 0);
1799 static int save_stash(int argc, const char **argv, const char *prefix)
1801 int keep_index = -1;
1802 int only_staged = 0;
1803 int patch_mode = 0;
1804 int include_untracked = 0;
1805 int quiet = 0;
1806 int ret = 0;
1807 const char *stash_msg = NULL;
1808 struct pathspec ps;
1809 struct strbuf stash_msg_buf = STRBUF_INIT;
1810 struct option options[] = {
1811 OPT_BOOL('k', "keep-index", &keep_index,
1812 N_("keep index")),
1813 OPT_BOOL('S', "staged", &only_staged,
1814 N_("stash staged changes only")),
1815 OPT_BOOL('p', "patch", &patch_mode,
1816 N_("stash in patch mode")),
1817 OPT__QUIET(&quiet, N_("quiet mode")),
1818 OPT_BOOL('u', "include-untracked", &include_untracked,
1819 N_("include untracked files in stash")),
1820 OPT_SET_INT('a', "all", &include_untracked,
1821 N_("include ignore files"), 2),
1822 OPT_STRING('m', "message", &stash_msg, "message",
1823 N_("stash message")),
1824 OPT_END()
1827 argc = parse_options(argc, argv, prefix, options,
1828 git_stash_save_usage,
1829 PARSE_OPT_KEEP_DASHDASH);
1831 if (argc)
1832 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
1834 memset(&ps, 0, sizeof(ps));
1835 ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
1836 patch_mode, include_untracked, only_staged);
1838 strbuf_release(&stash_msg_buf);
1839 return ret;
1842 int cmd_stash(int argc, const char **argv, const char *prefix)
1844 pid_t pid = getpid();
1845 const char *index_file;
1846 struct strvec args = STRVEC_INIT;
1847 parse_opt_subcommand_fn *fn = NULL;
1848 struct option options[] = {
1849 OPT_SUBCOMMAND("apply", &fn, apply_stash),
1850 OPT_SUBCOMMAND("clear", &fn, clear_stash),
1851 OPT_SUBCOMMAND("drop", &fn, drop_stash),
1852 OPT_SUBCOMMAND("pop", &fn, pop_stash),
1853 OPT_SUBCOMMAND("branch", &fn, branch_stash),
1854 OPT_SUBCOMMAND("list", &fn, list_stash),
1855 OPT_SUBCOMMAND("show", &fn, show_stash),
1856 OPT_SUBCOMMAND("store", &fn, store_stash),
1857 OPT_SUBCOMMAND("create", &fn, create_stash),
1858 OPT_SUBCOMMAND("push", &fn, push_stash_unassumed),
1859 OPT_SUBCOMMAND_F("save", &fn, save_stash, PARSE_OPT_NOCOMPLETE),
1860 OPT_END()
1863 git_config(git_stash_config, NULL);
1865 argc = parse_options(argc, argv, prefix, options, git_stash_usage,
1866 PARSE_OPT_SUBCOMMAND_OPTIONAL |
1867 PARSE_OPT_KEEP_UNKNOWN_OPT |
1868 PARSE_OPT_KEEP_DASHDASH);
1870 prepare_repo_settings(the_repository);
1871 the_repository->settings.command_requires_full_index = 0;
1873 index_file = get_index_file();
1874 strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
1875 (uintmax_t)pid);
1877 if (fn)
1878 return !!fn(argc, argv, prefix);
1879 else if (!argc)
1880 return !!push_stash_unassumed(0, NULL, prefix);
1882 /* Assume 'stash push' */
1883 strvec_push(&args, "push");
1884 strvec_pushv(&args, argv);
1885 return !!push_stash(args.nr, args.v, prefix, 1);