Start the 2.48 cycle
[git/gitster.git] / builtin / stash.c
blob1399a1bbe2c222ed3e1c33ac2dd17bd1148f709c
1 #define USE_THE_REPOSITORY_VARIABLE
2 #include "builtin.h"
3 #include "abspath.h"
4 #include "config.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "hash.h"
8 #include "hex.h"
9 #include "object-name.h"
10 #include "parse-options.h"
11 #include "refs.h"
12 #include "lockfile.h"
13 #include "cache-tree.h"
14 #include "unpack-trees.h"
15 #include "merge-recursive.h"
16 #include "merge-ort-wrappers.h"
17 #include "strvec.h"
18 #include "run-command.h"
19 #include "dir.h"
20 #include "entry.h"
21 #include "preload-index.h"
22 #include "read-cache.h"
23 #include "repository.h"
24 #include "rerere.h"
25 #include "revision.h"
26 #include "setup.h"
27 #include "sparse-index.h"
28 #include "log-tree.h"
29 #include "diffcore.h"
30 #include "reflog.h"
31 #include "add-interactive.h"
33 #define INCLUDE_ALL_FILES 2
35 #define BUILTIN_STASH_LIST_USAGE \
36 N_("git stash list [<log-options>]")
37 #define BUILTIN_STASH_SHOW_USAGE \
38 N_("git stash show [-u | --include-untracked | --only-untracked] [<diff-options>] [<stash>]")
39 #define BUILTIN_STASH_DROP_USAGE \
40 N_("git stash drop [-q | --quiet] [<stash>]")
41 #define BUILTIN_STASH_POP_USAGE \
42 N_("git stash pop [--index] [-q | --quiet] [<stash>]")
43 #define BUILTIN_STASH_APPLY_USAGE \
44 N_("git stash apply [--index] [-q | --quiet] [<stash>]")
45 #define BUILTIN_STASH_BRANCH_USAGE \
46 N_("git stash branch <branchname> [<stash>]")
47 #define BUILTIN_STASH_STORE_USAGE \
48 N_("git stash store [(-m | --message) <message>] [-q | --quiet] <commit>")
49 #define BUILTIN_STASH_PUSH_USAGE \
50 N_("git stash [push [-p | --patch] [-S | --staged] [-k | --[no-]keep-index] [-q | --quiet]\n" \
51 " [-u | --include-untracked] [-a | --all] [(-m | --message) <message>]\n" \
52 " [--pathspec-from-file=<file> [--pathspec-file-nul]]\n" \
53 " [--] [<pathspec>...]]")
54 #define BUILTIN_STASH_SAVE_USAGE \
55 N_("git stash save [-p | --patch] [-S | --staged] [-k | --[no-]keep-index] [-q | --quiet]\n" \
56 " [-u | --include-untracked] [-a | --all] [<message>]")
57 #define BUILTIN_STASH_CREATE_USAGE \
58 N_("git stash create [<message>]")
59 #define BUILTIN_STASH_CLEAR_USAGE \
60 "git stash clear"
62 static const char * const git_stash_usage[] = {
63 BUILTIN_STASH_LIST_USAGE,
64 BUILTIN_STASH_SHOW_USAGE,
65 BUILTIN_STASH_DROP_USAGE,
66 BUILTIN_STASH_POP_USAGE,
67 BUILTIN_STASH_APPLY_USAGE,
68 BUILTIN_STASH_BRANCH_USAGE,
69 BUILTIN_STASH_PUSH_USAGE,
70 BUILTIN_STASH_SAVE_USAGE,
71 BUILTIN_STASH_CLEAR_USAGE,
72 BUILTIN_STASH_CREATE_USAGE,
73 BUILTIN_STASH_STORE_USAGE,
74 NULL
77 static const char * const git_stash_list_usage[] = {
78 BUILTIN_STASH_LIST_USAGE,
79 NULL
82 static const char * const git_stash_show_usage[] = {
83 BUILTIN_STASH_SHOW_USAGE,
84 NULL
87 static const char * const git_stash_drop_usage[] = {
88 BUILTIN_STASH_DROP_USAGE,
89 NULL
92 static const char * const git_stash_pop_usage[] = {
93 BUILTIN_STASH_POP_USAGE,
94 NULL
97 static const char * const git_stash_apply_usage[] = {
98 BUILTIN_STASH_APPLY_USAGE,
99 NULL
102 static const char * const git_stash_branch_usage[] = {
103 BUILTIN_STASH_BRANCH_USAGE,
104 NULL
107 static const char * const git_stash_clear_usage[] = {
108 BUILTIN_STASH_CLEAR_USAGE,
109 NULL
112 static const char * const git_stash_store_usage[] = {
113 BUILTIN_STASH_STORE_USAGE,
114 NULL
117 static const char * const git_stash_push_usage[] = {
118 BUILTIN_STASH_PUSH_USAGE,
119 NULL
122 static const char * const git_stash_save_usage[] = {
123 BUILTIN_STASH_SAVE_USAGE,
124 NULL
127 static const char ref_stash[] = "refs/stash";
128 static struct strbuf stash_index_path = STRBUF_INIT;
131 * w_commit is set to the commit containing the working tree
132 * b_commit is set to the base commit
133 * i_commit is set to the commit containing the index tree
134 * u_commit is set to the commit containing the untracked files tree
135 * w_tree is set to the working tree
136 * b_tree is set to the base tree
137 * i_tree is set to the index tree
138 * u_tree is set to the untracked files tree
140 struct stash_info {
141 struct object_id w_commit;
142 struct object_id b_commit;
143 struct object_id i_commit;
144 struct object_id u_commit;
145 struct object_id w_tree;
146 struct object_id b_tree;
147 struct object_id i_tree;
148 struct object_id u_tree;
149 struct strbuf revision;
150 int is_stash_ref;
151 int has_u;
154 #define STASH_INFO_INIT { \
155 .revision = STRBUF_INIT, \
158 static void free_stash_info(struct stash_info *info)
160 strbuf_release(&info->revision);
163 static void assert_stash_like(struct stash_info *info, const char *revision)
165 if (get_oidf(&info->b_commit, "%s^1", revision) ||
166 get_oidf(&info->w_tree, "%s:", revision) ||
167 get_oidf(&info->b_tree, "%s^1:", revision) ||
168 get_oidf(&info->i_tree, "%s^2:", revision))
169 die(_("'%s' is not a stash-like commit"), revision);
172 static int get_stash_info(struct stash_info *info, int argc, const char **argv)
174 int ret;
175 char *end_of_rev;
176 char *expanded_ref;
177 const char *revision;
178 const char *commit = NULL;
179 struct object_id dummy;
180 struct strbuf symbolic = STRBUF_INIT;
182 if (argc > 1) {
183 int i;
184 struct strbuf refs_msg = STRBUF_INIT;
186 for (i = 0; i < argc; i++)
187 strbuf_addf(&refs_msg, " '%s'", argv[i]);
189 fprintf_ln(stderr, _("Too many revisions specified:%s"),
190 refs_msg.buf);
191 strbuf_release(&refs_msg);
193 return -1;
196 if (argc == 1)
197 commit = argv[0];
199 if (!commit) {
200 if (!refs_ref_exists(get_main_ref_store(the_repository), ref_stash)) {
201 fprintf_ln(stderr, _("No stash entries found."));
202 return -1;
205 strbuf_addf(&info->revision, "%s@{0}", ref_stash);
206 } else if (strspn(commit, "0123456789") == strlen(commit)) {
207 strbuf_addf(&info->revision, "%s@{%s}", ref_stash, commit);
208 } else {
209 strbuf_addstr(&info->revision, commit);
212 revision = info->revision.buf;
214 if (repo_get_oid(the_repository, revision, &info->w_commit))
215 return error(_("%s is not a valid reference"), revision);
217 assert_stash_like(info, revision);
219 info->has_u = !get_oidf(&info->u_tree, "%s^3:", revision);
221 end_of_rev = strchrnul(revision, '@');
222 strbuf_add(&symbolic, revision, end_of_rev - revision);
224 ret = repo_dwim_ref(the_repository, symbolic.buf, symbolic.len,
225 &dummy, &expanded_ref, 0);
226 strbuf_release(&symbolic);
227 switch (ret) {
228 case 0: /* Not found, but valid ref */
229 info->is_stash_ref = 0;
230 break;
231 case 1:
232 info->is_stash_ref = !strcmp(expanded_ref, ref_stash);
233 break;
234 default: /* Invalid or ambiguous */
235 break;
238 free(expanded_ref);
239 return !(ret == 0 || ret == 1);
242 static int do_clear_stash(void)
244 struct object_id obj;
245 if (repo_get_oid(the_repository, ref_stash, &obj))
246 return 0;
248 return refs_delete_ref(get_main_ref_store(the_repository), NULL,
249 ref_stash, &obj, 0);
252 static int clear_stash(int argc, const char **argv, const char *prefix)
254 struct option options[] = {
255 OPT_END()
258 argc = parse_options(argc, argv, prefix, options,
259 git_stash_clear_usage,
260 PARSE_OPT_STOP_AT_NON_OPTION);
262 if (argc)
263 return error(_("git stash clear with arguments is "
264 "unimplemented"));
266 return do_clear_stash();
269 static int reset_tree(struct object_id *i_tree, int update, int reset)
271 int nr_trees = 1;
272 struct unpack_trees_options opts;
273 struct tree_desc t[MAX_UNPACK_TREES];
274 struct tree *tree;
275 struct lock_file lock_file = LOCK_INIT;
277 repo_read_index_preload(the_repository, NULL, 0);
278 if (refresh_index(the_repository->index, REFRESH_QUIET, NULL, NULL, NULL))
279 return -1;
281 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
283 memset(&opts, 0, sizeof(opts));
285 tree = parse_tree_indirect(i_tree);
286 if (parse_tree(tree))
287 return -1;
289 init_tree_desc(t, &tree->object.oid, tree->buffer, tree->size);
291 opts.head_idx = 1;
292 opts.src_index = the_repository->index;
293 opts.dst_index = the_repository->index;
294 opts.merge = 1;
295 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
296 opts.update = update;
297 if (update)
298 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
299 opts.fn = oneway_merge;
301 if (unpack_trees(nr_trees, t, &opts))
302 return -1;
304 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
305 return error(_("unable to write new index file"));
307 return 0;
310 static int diff_tree_binary(struct strbuf *out, struct object_id *w_commit)
312 struct child_process cp = CHILD_PROCESS_INIT;
313 const char *w_commit_hex = oid_to_hex(w_commit);
316 * Diff-tree would not be very hard to replace with a native function,
317 * however it should be done together with apply_cached.
319 cp.git_cmd = 1;
320 strvec_pushl(&cp.args, "diff-tree", "--binary", NULL);
321 strvec_pushf(&cp.args, "%s^2^..%s^2", w_commit_hex, w_commit_hex);
323 return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
326 static int apply_cached(struct strbuf *out)
328 struct child_process cp = CHILD_PROCESS_INIT;
331 * Apply currently only reads either from stdin or a file, thus
332 * apply_all_patches would have to be updated to optionally take a
333 * buffer.
335 cp.git_cmd = 1;
336 strvec_pushl(&cp.args, "apply", "--cached", NULL);
337 return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
340 static int reset_head(void)
342 struct child_process cp = CHILD_PROCESS_INIT;
345 * Reset is overall quite simple, however there is no current public
346 * API for resetting.
348 cp.git_cmd = 1;
349 strvec_pushl(&cp.args, "reset", "--quiet", "--refresh", NULL);
351 return run_command(&cp);
354 static int is_path_a_directory(const char *path)
357 * This function differs from abspath.c:is_directory() in that
358 * here we use lstat() instead of stat(); we do not want to
359 * follow symbolic links here.
361 struct stat st;
362 return (!lstat(path, &st) && S_ISDIR(st.st_mode));
365 static void add_diff_to_buf(struct diff_queue_struct *q,
366 struct diff_options *options UNUSED,
367 void *data)
369 int i;
371 for (i = 0; i < q->nr; i++) {
372 if (is_path_a_directory(q->queue[i]->one->path))
373 continue;
375 strbuf_addstr(data, q->queue[i]->one->path);
377 /* NUL-terminate: will be fed to update-index -z */
378 strbuf_addch(data, '\0');
382 static int restore_untracked(struct object_id *u_tree)
384 int res;
385 struct child_process cp = CHILD_PROCESS_INIT;
388 * We need to run restore files from a given index, but without
389 * affecting the current index, so we use GIT_INDEX_FILE with
390 * run_command to fork processes that will not interfere.
392 cp.git_cmd = 1;
393 strvec_push(&cp.args, "read-tree");
394 strvec_push(&cp.args, oid_to_hex(u_tree));
395 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
396 stash_index_path.buf);
397 if (run_command(&cp)) {
398 remove_path(stash_index_path.buf);
399 return -1;
402 child_process_init(&cp);
403 cp.git_cmd = 1;
404 strvec_pushl(&cp.args, "checkout-index", "--all", NULL);
405 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
406 stash_index_path.buf);
408 res = run_command(&cp);
409 remove_path(stash_index_path.buf);
410 return res;
413 static void unstage_changes_unless_new(struct object_id *orig_tree)
416 * When we enter this function, there has been a clean merge of
417 * relevant trees, and the merge logic always stages whatever merges
418 * cleanly. We want to unstage those changes, unless it corresponds
419 * to a file that didn't exist as of orig_tree.
421 * However, if any SKIP_WORKTREE path is modified relative to
422 * orig_tree, then we want to clear the SKIP_WORKTREE bit and write
423 * it to the worktree before unstaging.
426 struct checkout state = CHECKOUT_INIT;
427 struct diff_options diff_opts;
428 struct lock_file lock = LOCK_INIT;
429 int i;
431 /* If any entries have skip_worktree set, we'll have to check 'em out */
432 state.force = 1;
433 state.quiet = 1;
434 state.refresh_cache = 1;
435 state.istate = the_repository->index;
438 * Step 1: get a difference between orig_tree (which corresponding
439 * to the index before a merge was run) and the current index
440 * (reflecting the changes brought in by the merge).
442 repo_diff_setup(the_repository, &diff_opts);
443 diff_opts.flags.recursive = 1;
444 diff_opts.detect_rename = 0;
445 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
446 diff_setup_done(&diff_opts);
448 do_diff_cache(orig_tree, &diff_opts);
449 diffcore_std(&diff_opts);
451 /* Iterate over the paths that changed due to the merge... */
452 for (i = 0; i < diff_queued_diff.nr; i++) {
453 struct diff_filepair *p;
454 struct cache_entry *ce;
455 int pos;
457 /* Look up the path's position in the current index. */
458 p = diff_queued_diff.queue[i];
459 pos = index_name_pos(the_repository->index, p->two->path,
460 strlen(p->two->path));
463 * Step 2: Place changes in the working tree
465 * Stash is about restoring changes *to the working tree*.
466 * So if the merge successfully got a new version of some
467 * path, but left it out of the working tree, then clear the
468 * SKIP_WORKTREE bit and write it to the working tree.
470 if (pos >= 0 && ce_skip_worktree(the_repository->index->cache[pos])) {
471 struct stat st;
473 ce = the_repository->index->cache[pos];
474 if (!lstat(ce->name, &st)) {
475 /* Conflicting path present; relocate it */
476 struct strbuf new_path = STRBUF_INIT;
477 int fd;
479 strbuf_addf(&new_path,
480 "%s.stash.XXXXXX", ce->name);
481 fd = xmkstemp(new_path.buf);
482 close(fd);
483 printf(_("WARNING: Untracked file in way of "
484 "tracked file! Renaming\n "
485 " %s -> %s\n"
486 " to make room.\n"),
487 ce->name, new_path.buf);
488 if (rename(ce->name, new_path.buf))
489 die("Failed to move %s to %s",
490 ce->name, new_path.buf);
491 strbuf_release(&new_path);
493 checkout_entry(ce, &state, NULL, NULL);
494 ce->ce_flags &= ~CE_SKIP_WORKTREE;
498 * Step 3: "unstage" changes, as long as they are still tracked
500 if (p->one->oid_valid) {
502 * Path existed in orig_tree; restore index entry
503 * from that tree in order to "unstage" the changes.
505 int option = ADD_CACHE_OK_TO_REPLACE;
506 if (pos < 0)
507 option = ADD_CACHE_OK_TO_ADD;
509 ce = make_cache_entry(the_repository->index,
510 p->one->mode,
511 &p->one->oid,
512 p->one->path,
513 0, 0);
514 add_index_entry(the_repository->index, ce, option);
517 diff_flush(&diff_opts);
520 * Step 4: write the new index to disk
522 repo_hold_locked_index(the_repository, &lock, LOCK_DIE_ON_ERROR);
523 if (write_locked_index(the_repository->index, &lock,
524 COMMIT_LOCK | SKIP_IF_UNCHANGED))
525 die(_("could not write index"));
528 static int do_apply_stash(const char *prefix, struct stash_info *info,
529 int index, int quiet)
531 int clean, ret;
532 int has_index = index;
533 struct merge_options o;
534 struct object_id c_tree;
535 struct object_id index_tree;
536 struct tree *head, *merge, *merge_base;
537 struct lock_file lock = LOCK_INIT;
539 repo_read_index_preload(the_repository, NULL, 0);
540 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
541 NULL, NULL, NULL))
542 return error(_("could not write index"));
544 if (write_index_as_tree(&c_tree, the_repository->index,
545 repo_get_index_file(the_repository), 0, NULL))
546 return error(_("cannot apply a stash in the middle of a merge"));
548 if (index) {
549 if (oideq(&info->b_tree, &info->i_tree) ||
550 oideq(&c_tree, &info->i_tree)) {
551 has_index = 0;
552 } else {
553 struct strbuf out = STRBUF_INIT;
555 if (diff_tree_binary(&out, &info->w_commit)) {
556 strbuf_release(&out);
557 return error(_("could not generate diff %s^!."),
558 oid_to_hex(&info->w_commit));
561 ret = apply_cached(&out);
562 strbuf_release(&out);
563 if (ret)
564 return error(_("conflicts in index. "
565 "Try without --index."));
567 discard_index(the_repository->index);
568 repo_read_index(the_repository);
569 if (write_index_as_tree(&index_tree, the_repository->index,
570 repo_get_index_file(the_repository), 0, NULL))
571 return error(_("could not save index tree"));
573 reset_head();
574 discard_index(the_repository->index);
575 repo_read_index(the_repository);
579 init_ui_merge_options(&o, the_repository);
581 o.branch1 = "Updated upstream";
582 o.branch2 = "Stashed changes";
583 o.ancestor = "Stash base";
585 if (oideq(&info->b_tree, &c_tree))
586 o.branch1 = "Version stash was based on";
588 if (quiet)
589 o.verbosity = 0;
591 if (o.verbosity >= 3)
592 printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
594 head = lookup_tree(o.repo, &c_tree);
595 merge = lookup_tree(o.repo, &info->w_tree);
596 merge_base = lookup_tree(o.repo, &info->b_tree);
598 repo_hold_locked_index(o.repo, &lock, LOCK_DIE_ON_ERROR);
599 clean = merge_ort_nonrecursive(&o, head, merge, merge_base);
602 * If 'clean' >= 0, reverse the value for 'ret' so 'ret' is 0 when the
603 * merge was clean, and nonzero if the merge was unclean or encountered
604 * an error.
606 ret = clean >= 0 ? !clean : clean;
608 if (ret < 0)
609 rollback_lock_file(&lock);
610 else if (write_locked_index(o.repo->index, &lock,
611 COMMIT_LOCK | SKIP_IF_UNCHANGED))
612 ret = error(_("could not write index"));
614 if (ret) {
615 repo_rerere(the_repository, 0);
617 if (index)
618 fprintf_ln(stderr, _("Index was not unstashed."));
620 goto restore_untracked;
623 if (has_index) {
624 if (reset_tree(&index_tree, 0, 0))
625 ret = -1;
626 } else {
627 unstage_changes_unless_new(&c_tree);
630 restore_untracked:
631 if (info->has_u && restore_untracked(&info->u_tree))
632 ret = error(_("could not restore untracked files from stash"));
634 if (!quiet) {
635 struct child_process cp = CHILD_PROCESS_INIT;
638 * Status is quite simple and could be replaced with calls to
639 * wt_status in the future, but it adds complexities which may
640 * require more tests.
642 cp.git_cmd = 1;
643 cp.dir = prefix;
644 strvec_pushf(&cp.env, GIT_WORK_TREE_ENVIRONMENT"=%s",
645 absolute_path(repo_get_work_tree(the_repository)));
646 strvec_pushf(&cp.env, GIT_DIR_ENVIRONMENT"=%s",
647 absolute_path(repo_get_git_dir(the_repository)));
648 strvec_push(&cp.args, "status");
649 run_command(&cp);
652 return ret;
655 static int apply_stash(int argc, const char **argv, const char *prefix)
657 int ret = -1;
658 int quiet = 0;
659 int index = 0;
660 struct stash_info info = STASH_INFO_INIT;
661 struct option options[] = {
662 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
663 OPT_BOOL(0, "index", &index,
664 N_("attempt to recreate the index")),
665 OPT_END()
668 argc = parse_options(argc, argv, prefix, options,
669 git_stash_apply_usage, 0);
671 if (get_stash_info(&info, argc, argv))
672 goto cleanup;
674 ret = do_apply_stash(prefix, &info, index, quiet);
675 cleanup:
676 free_stash_info(&info);
677 return ret;
680 static int reject_reflog_ent(struct object_id *ooid UNUSED,
681 struct object_id *noid UNUSED,
682 const char *email UNUSED,
683 timestamp_t timestamp UNUSED,
684 int tz UNUSED, const char *message UNUSED,
685 void *cb_data UNUSED)
687 return 1;
690 static int reflog_is_empty(const char *refname)
692 return !refs_for_each_reflog_ent(get_main_ref_store(the_repository),
693 refname, reject_reflog_ent, NULL);
696 static int do_drop_stash(struct stash_info *info, int quiet)
698 if (!reflog_delete(info->revision.buf,
699 EXPIRE_REFLOGS_REWRITE | EXPIRE_REFLOGS_UPDATE_REF,
700 0)) {
701 if (!quiet)
702 printf_ln(_("Dropped %s (%s)"), info->revision.buf,
703 oid_to_hex(&info->w_commit));
704 } else {
705 return error(_("%s: Could not drop stash entry"),
706 info->revision.buf);
709 if (reflog_is_empty(ref_stash))
710 do_clear_stash();
712 return 0;
715 static int get_stash_info_assert(struct stash_info *info, int argc,
716 const char **argv)
718 int ret = get_stash_info(info, argc, argv);
720 if (ret < 0)
721 return ret;
723 if (!info->is_stash_ref)
724 return error(_("'%s' is not a stash reference"), info->revision.buf);
726 return 0;
729 static int drop_stash(int argc, const char **argv, const char *prefix)
731 int ret = -1;
732 int quiet = 0;
733 struct stash_info info = STASH_INFO_INIT;
734 struct option options[] = {
735 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
736 OPT_END()
739 argc = parse_options(argc, argv, prefix, options,
740 git_stash_drop_usage, 0);
742 if (get_stash_info_assert(&info, argc, argv))
743 goto cleanup;
745 ret = do_drop_stash(&info, quiet);
746 cleanup:
747 free_stash_info(&info);
748 return ret;
751 static int pop_stash(int argc, const char **argv, const char *prefix)
753 int ret = -1;
754 int index = 0;
755 int quiet = 0;
756 struct stash_info info = STASH_INFO_INIT;
757 struct option options[] = {
758 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
759 OPT_BOOL(0, "index", &index,
760 N_("attempt to recreate the index")),
761 OPT_END()
764 argc = parse_options(argc, argv, prefix, options,
765 git_stash_pop_usage, 0);
767 if (get_stash_info_assert(&info, argc, argv))
768 goto cleanup;
770 if ((ret = do_apply_stash(prefix, &info, index, quiet)))
771 printf_ln(_("The stash entry is kept in case "
772 "you need it again."));
773 else
774 ret = do_drop_stash(&info, quiet);
776 cleanup:
777 free_stash_info(&info);
778 return ret;
781 static int branch_stash(int argc, const char **argv, const char *prefix)
783 int ret = -1;
784 const char *branch = NULL;
785 struct stash_info info = STASH_INFO_INIT;
786 struct child_process cp = CHILD_PROCESS_INIT;
787 struct option options[] = {
788 OPT_END()
791 argc = parse_options(argc, argv, prefix, options,
792 git_stash_branch_usage, 0);
794 if (!argc) {
795 fprintf_ln(stderr, _("No branch name specified"));
796 return -1;
799 branch = argv[0];
801 if (get_stash_info(&info, argc - 1, argv + 1))
802 goto cleanup;
804 cp.git_cmd = 1;
805 strvec_pushl(&cp.args, "checkout", "-b", NULL);
806 strvec_push(&cp.args, branch);
807 strvec_push(&cp.args, oid_to_hex(&info.b_commit));
808 ret = run_command(&cp);
809 if (!ret)
810 ret = do_apply_stash(prefix, &info, 1, 0);
811 if (!ret && info.is_stash_ref)
812 ret = do_drop_stash(&info, 0);
814 cleanup:
815 free_stash_info(&info);
816 return ret;
819 static int list_stash(int argc, const char **argv, const char *prefix)
821 struct child_process cp = CHILD_PROCESS_INIT;
822 struct option options[] = {
823 OPT_END()
826 argc = parse_options(argc, argv, prefix, options,
827 git_stash_list_usage,
828 PARSE_OPT_KEEP_UNKNOWN_OPT);
830 if (!refs_ref_exists(get_main_ref_store(the_repository), ref_stash))
831 return 0;
833 cp.git_cmd = 1;
834 strvec_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
835 "--first-parent", NULL);
836 strvec_pushv(&cp.args, argv);
837 strvec_push(&cp.args, ref_stash);
838 strvec_push(&cp.args, "--");
839 return run_command(&cp);
842 static int show_stat = 1;
843 static int show_patch;
844 static int show_include_untracked;
846 static int git_stash_config(const char *var, const char *value,
847 const struct config_context *ctx, void *cb)
849 if (!strcmp(var, "stash.showstat")) {
850 show_stat = git_config_bool(var, value);
851 return 0;
853 if (!strcmp(var, "stash.showpatch")) {
854 show_patch = git_config_bool(var, value);
855 return 0;
857 if (!strcmp(var, "stash.showincludeuntracked")) {
858 show_include_untracked = git_config_bool(var, value);
859 return 0;
861 return git_diff_basic_config(var, value, ctx, cb);
864 static void diff_include_untracked(const struct stash_info *info, struct diff_options *diff_opt)
866 const struct object_id *oid[] = { &info->w_commit, &info->u_tree };
867 struct tree *tree[ARRAY_SIZE(oid)];
868 struct tree_desc tree_desc[ARRAY_SIZE(oid)];
869 struct unpack_trees_options unpack_tree_opt = { 0 };
870 int i;
872 for (i = 0; i < ARRAY_SIZE(oid); i++) {
873 tree[i] = parse_tree_indirect(oid[i]);
874 if (parse_tree(tree[i]) < 0)
875 die(_("failed to parse tree"));
876 init_tree_desc(&tree_desc[i], &tree[i]->object.oid,
877 tree[i]->buffer, tree[i]->size);
880 unpack_tree_opt.head_idx = -1;
881 unpack_tree_opt.src_index = the_repository->index;
882 unpack_tree_opt.dst_index = the_repository->index;
883 unpack_tree_opt.merge = 1;
884 unpack_tree_opt.fn = stash_worktree_untracked_merge;
886 if (unpack_trees(ARRAY_SIZE(tree_desc), tree_desc, &unpack_tree_opt))
887 die(_("failed to unpack trees"));
889 do_diff_cache(&info->b_commit, diff_opt);
892 static int show_stash(int argc, const char **argv, const char *prefix)
894 int i;
895 int ret = -1;
896 struct stash_info info = STASH_INFO_INIT;
897 struct rev_info rev;
898 struct strvec stash_args = STRVEC_INIT;
899 struct strvec revision_args = STRVEC_INIT;
900 enum {
901 UNTRACKED_NONE,
902 UNTRACKED_INCLUDE,
903 UNTRACKED_ONLY
904 } show_untracked = show_include_untracked ? UNTRACKED_INCLUDE : UNTRACKED_NONE;
905 struct option options[] = {
906 OPT_SET_INT('u', "include-untracked", &show_untracked,
907 N_("include untracked files in the stash"),
908 UNTRACKED_INCLUDE),
909 OPT_SET_INT_F(0, "only-untracked", &show_untracked,
910 N_("only show untracked files in the stash"),
911 UNTRACKED_ONLY, PARSE_OPT_NONEG),
912 OPT_END()
914 int do_usage = 0;
916 init_diff_ui_defaults();
917 git_config(git_diff_ui_config, NULL);
918 repo_init_revisions(the_repository, &rev, prefix);
920 argc = parse_options(argc, argv, prefix, options, git_stash_show_usage,
921 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
922 PARSE_OPT_KEEP_DASHDASH);
924 strvec_push(&revision_args, argv[0]);
925 for (i = 1; i < argc; i++) {
926 if (argv[i][0] != '-')
927 strvec_push(&stash_args, argv[i]);
928 else
929 strvec_push(&revision_args, argv[i]);
932 if (get_stash_info(&info, stash_args.nr, stash_args.v))
933 goto cleanup;
936 * The config settings are applied only if there are not passed
937 * any options.
939 if (revision_args.nr == 1) {
940 if (show_stat)
941 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
943 if (show_patch)
944 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
946 if (!show_stat && !show_patch) {
947 ret = 0;
948 goto cleanup;
952 argc = setup_revisions(revision_args.nr, revision_args.v, &rev, NULL);
953 if (argc > 1)
954 goto usage;
955 if (!rev.diffopt.output_format) {
956 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
957 diff_setup_done(&rev.diffopt);
960 rev.diffopt.flags.recursive = 1;
961 setup_diff_pager(&rev.diffopt);
962 switch (show_untracked) {
963 case UNTRACKED_NONE:
964 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
965 break;
966 case UNTRACKED_ONLY:
967 if (info.has_u)
968 diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
969 break;
970 case UNTRACKED_INCLUDE:
971 if (info.has_u)
972 diff_include_untracked(&info, &rev.diffopt);
973 else
974 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
975 break;
977 log_tree_diff_flush(&rev);
979 ret = diff_result_code(&rev);
981 cleanup:
982 strvec_clear(&revision_args);
983 strvec_clear(&stash_args);
984 free_stash_info(&info);
985 release_revisions(&rev);
986 if (do_usage)
987 usage_with_options(git_stash_show_usage, options);
988 return ret;
989 usage:
990 do_usage = 1;
991 goto cleanup;
994 static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
995 int quiet)
997 struct stash_info info;
998 char revision[GIT_MAX_HEXSZ];
1000 oid_to_hex_r(revision, w_commit);
1001 assert_stash_like(&info, revision);
1003 if (!stash_msg)
1004 stash_msg = "Created via \"git stash store\".";
1006 if (refs_update_ref(get_main_ref_store(the_repository), stash_msg, ref_stash, w_commit, NULL,
1007 REF_FORCE_CREATE_REFLOG,
1008 quiet ? UPDATE_REFS_QUIET_ON_ERR :
1009 UPDATE_REFS_MSG_ON_ERR)) {
1010 if (!quiet) {
1011 fprintf_ln(stderr, _("Cannot update %s with %s"),
1012 ref_stash, oid_to_hex(w_commit));
1014 return -1;
1017 return 0;
1020 static int store_stash(int argc, const char **argv, const char *prefix)
1022 int quiet = 0;
1023 const char *stash_msg = NULL;
1024 struct object_id obj;
1025 struct object_context dummy = {0};
1026 struct option options[] = {
1027 OPT__QUIET(&quiet, N_("be quiet")),
1028 OPT_STRING('m', "message", &stash_msg, "message",
1029 N_("stash message")),
1030 OPT_END()
1032 int ret;
1034 argc = parse_options(argc, argv, prefix, options,
1035 git_stash_store_usage,
1036 PARSE_OPT_KEEP_UNKNOWN_OPT);
1038 if (argc != 1) {
1039 if (!quiet)
1040 fprintf_ln(stderr, _("\"git stash store\" requires one "
1041 "<commit> argument"));
1042 return -1;
1045 if (get_oid_with_context(the_repository,
1046 argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
1047 &dummy)) {
1048 if (!quiet)
1049 fprintf_ln(stderr, _("Cannot update %s with %s"),
1050 ref_stash, argv[0]);
1051 ret = -1;
1052 goto out;
1055 ret = do_store_stash(&obj, stash_msg, quiet);
1057 out:
1058 object_context_release(&dummy);
1059 return ret;
1062 static void add_pathspecs(struct strvec *args,
1063 const struct pathspec *ps) {
1064 int i;
1066 for (i = 0; i < ps->nr; i++)
1067 strvec_push(args, ps->items[i].original);
1071 * `untracked_files` will be filled with the names of untracked files.
1072 * The return value is:
1074 * = 0 if there are not any untracked files
1075 * > 0 if there are untracked files
1077 static int get_untracked_files(const struct pathspec *ps, int include_untracked,
1078 struct strbuf *untracked_files)
1080 int i;
1081 int found = 0;
1082 struct dir_struct dir = DIR_INIT;
1084 if (include_untracked != INCLUDE_ALL_FILES)
1085 setup_standard_excludes(&dir);
1087 fill_directory(&dir, the_repository->index, ps);
1088 for (i = 0; i < dir.nr; i++) {
1089 struct dir_entry *ent = dir.entries[i];
1090 found++;
1091 strbuf_addstr(untracked_files, ent->name);
1092 /* NUL-terminate: will be fed to update-index -z */
1093 strbuf_addch(untracked_files, '\0');
1096 dir_clear(&dir);
1097 return found;
1101 * The return value of `check_changes_tracked_files()` can be:
1103 * < 0 if there was an error
1104 * = 0 if there are no changes.
1105 * > 0 if there are changes.
1107 static int check_changes_tracked_files(const struct pathspec *ps)
1109 struct rev_info rev;
1110 struct object_id dummy;
1111 int ret = 0;
1113 /* No initial commit. */
1114 if (repo_get_oid(the_repository, "HEAD", &dummy))
1115 return -1;
1117 if (repo_read_index(the_repository) < 0)
1118 return -1;
1120 repo_init_revisions(the_repository, &rev, NULL);
1121 copy_pathspec(&rev.prune_data, ps);
1123 rev.diffopt.flags.quick = 1;
1124 rev.diffopt.flags.ignore_submodules = 1;
1125 rev.abbrev = 0;
1127 add_head_to_pending(&rev);
1128 diff_setup_done(&rev.diffopt);
1130 run_diff_index(&rev, DIFF_INDEX_CACHED);
1131 if (diff_result_code(&rev)) {
1132 ret = 1;
1133 goto done;
1136 run_diff_files(&rev, 0);
1137 if (diff_result_code(&rev)) {
1138 ret = 1;
1139 goto done;
1142 done:
1143 release_revisions(&rev);
1144 return ret;
1148 * The function will fill `untracked_files` with the names of untracked files
1149 * It will return 1 if there were any changes and 0 if there were not.
1151 static int check_changes(const struct pathspec *ps, int include_untracked,
1152 struct strbuf *untracked_files)
1154 int ret = 0;
1155 if (check_changes_tracked_files(ps))
1156 ret = 1;
1158 if (include_untracked && get_untracked_files(ps, include_untracked,
1159 untracked_files))
1160 ret = 1;
1162 return ret;
1165 static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
1166 struct strbuf files)
1168 int ret = 0;
1169 struct strbuf untracked_msg = STRBUF_INIT;
1170 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1171 struct index_state istate = INDEX_STATE_INIT(the_repository);
1173 cp_upd_index.git_cmd = 1;
1174 strvec_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
1175 "--remove", "--stdin", NULL);
1176 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1177 stash_index_path.buf);
1179 strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
1180 if (pipe_command(&cp_upd_index, files.buf, files.len, NULL, 0,
1181 NULL, 0)) {
1182 ret = -1;
1183 goto done;
1186 if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
1187 NULL)) {
1188 ret = -1;
1189 goto done;
1192 if (commit_tree(untracked_msg.buf, untracked_msg.len,
1193 &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
1194 ret = -1;
1195 goto done;
1198 done:
1199 release_index(&istate);
1200 strbuf_release(&untracked_msg);
1201 remove_path(stash_index_path.buf);
1202 return ret;
1205 static int stash_staged(struct stash_info *info, struct strbuf *out_patch,
1206 int quiet)
1208 int ret = 0;
1209 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1210 struct index_state istate = INDEX_STATE_INIT(the_repository);
1212 if (write_index_as_tree(&info->w_tree, &istate, the_repository->index_file,
1213 0, NULL)) {
1214 ret = -1;
1215 goto done;
1218 cp_diff_tree.git_cmd = 1;
1219 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "--binary",
1220 "-U1", "HEAD", oid_to_hex(&info->w_tree), "--", NULL);
1221 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1222 ret = -1;
1223 goto done;
1226 if (!out_patch->len) {
1227 if (!quiet)
1228 fprintf_ln(stderr, _("No staged changes"));
1229 ret = 1;
1232 done:
1233 release_index(&istate);
1234 return ret;
1237 static int stash_patch(struct stash_info *info, const struct pathspec *ps,
1238 struct strbuf *out_patch, int quiet)
1240 int ret = 0;
1241 struct child_process cp_read_tree = CHILD_PROCESS_INIT;
1242 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1243 struct index_state istate = INDEX_STATE_INIT(the_repository);
1244 char *old_index_env = NULL, *old_repo_index_file;
1246 remove_path(stash_index_path.buf);
1248 cp_read_tree.git_cmd = 1;
1249 strvec_pushl(&cp_read_tree.args, "read-tree", "HEAD", NULL);
1250 strvec_pushf(&cp_read_tree.env, "GIT_INDEX_FILE=%s",
1251 stash_index_path.buf);
1252 if (run_command(&cp_read_tree)) {
1253 ret = -1;
1254 goto done;
1257 /* Find out what the user wants. */
1258 old_repo_index_file = the_repository->index_file;
1259 the_repository->index_file = stash_index_path.buf;
1260 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
1261 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
1263 ret = !!run_add_p(the_repository, ADD_P_STASH, NULL, ps);
1265 the_repository->index_file = old_repo_index_file;
1266 if (old_index_env && *old_index_env)
1267 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
1268 else
1269 unsetenv(INDEX_ENVIRONMENT);
1270 FREE_AND_NULL(old_index_env);
1272 /* State of the working tree. */
1273 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1274 NULL)) {
1275 ret = -1;
1276 goto done;
1279 cp_diff_tree.git_cmd = 1;
1280 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1281 oid_to_hex(&info->w_tree), "--", NULL);
1282 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1283 ret = -1;
1284 goto done;
1287 if (!out_patch->len) {
1288 if (!quiet)
1289 fprintf_ln(stderr, _("No changes selected"));
1290 ret = 1;
1293 done:
1294 release_index(&istate);
1295 remove_path(stash_index_path.buf);
1296 return ret;
1299 static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
1301 int ret = 0;
1302 struct rev_info rev;
1303 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1304 struct strbuf diff_output = STRBUF_INIT;
1305 struct index_state istate = INDEX_STATE_INIT(the_repository);
1307 repo_init_revisions(the_repository, &rev, NULL);
1308 copy_pathspec(&rev.prune_data, ps);
1310 set_alternate_index_output(stash_index_path.buf);
1311 if (reset_tree(&info->i_tree, 0, 0)) {
1312 ret = -1;
1313 goto done;
1315 set_alternate_index_output(NULL);
1317 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1318 rev.diffopt.format_callback = add_diff_to_buf;
1319 rev.diffopt.format_callback_data = &diff_output;
1321 if (repo_read_index_preload(the_repository, &rev.diffopt.pathspec, 0) < 0) {
1322 ret = -1;
1323 goto done;
1326 add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1327 "");
1328 run_diff_index(&rev, 0);
1330 cp_upd_index.git_cmd = 1;
1331 strvec_pushl(&cp_upd_index.args, "update-index",
1332 "--ignore-skip-worktree-entries",
1333 "-z", "--add", "--remove", "--stdin", NULL);
1334 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1335 stash_index_path.buf);
1337 if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1338 NULL, 0, NULL, 0)) {
1339 ret = -1;
1340 goto done;
1343 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1344 NULL)) {
1345 ret = -1;
1346 goto done;
1349 done:
1350 release_index(&istate);
1351 release_revisions(&rev);
1352 strbuf_release(&diff_output);
1353 remove_path(stash_index_path.buf);
1354 return ret;
1357 static int do_create_stash(const struct pathspec *ps, struct strbuf *stash_msg_buf,
1358 int include_untracked, int patch_mode, int only_staged,
1359 struct stash_info *info, struct strbuf *patch,
1360 int quiet)
1362 int ret = 0;
1363 int flags = 0;
1364 int untracked_commit_option = 0;
1365 const char *head_short_sha1 = NULL;
1366 const char *branch_ref = NULL;
1367 const char *branch_name = "(no branch)";
1368 struct commit *head_commit = NULL;
1369 struct commit_list *parents = NULL;
1370 struct strbuf msg = STRBUF_INIT;
1371 struct strbuf commit_tree_label = STRBUF_INIT;
1372 struct strbuf untracked_files = STRBUF_INIT;
1374 prepare_fallback_ident("git stash", "git@stash");
1376 repo_read_index_preload(the_repository, NULL, 0);
1377 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1378 NULL, NULL, NULL) < 0) {
1379 ret = error(_("could not write index"));
1380 goto done;
1383 if (repo_get_oid(the_repository, "HEAD", &info->b_commit)) {
1384 if (!quiet)
1385 fprintf_ln(stderr, _("You do not have "
1386 "the initial commit yet"));
1387 ret = -1;
1388 goto done;
1389 } else {
1390 head_commit = lookup_commit(the_repository, &info->b_commit);
1393 if (!check_changes(ps, include_untracked, &untracked_files)) {
1394 ret = 1;
1395 goto done;
1398 branch_ref = refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
1399 "HEAD", 0, NULL, &flags);
1400 if (flags & REF_ISSYMREF)
1401 skip_prefix(branch_ref, "refs/heads/", &branch_name);
1402 head_short_sha1 = repo_find_unique_abbrev(the_repository,
1403 &head_commit->object.oid,
1404 DEFAULT_ABBREV);
1405 strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1406 pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1408 strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1409 commit_list_insert(head_commit, &parents);
1410 if (write_index_as_tree(&info->i_tree, the_repository->index,
1411 repo_get_index_file(the_repository), 0, NULL) ||
1412 commit_tree(commit_tree_label.buf, commit_tree_label.len,
1413 &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1414 if (!quiet)
1415 fprintf_ln(stderr, _("Cannot save the current "
1416 "index state"));
1417 ret = -1;
1418 goto done;
1421 free_commit_list(parents);
1422 parents = NULL;
1424 if (include_untracked) {
1425 if (save_untracked_files(info, &msg, untracked_files)) {
1426 if (!quiet)
1427 fprintf_ln(stderr, _("Cannot save "
1428 "the untracked files"));
1429 ret = -1;
1430 goto done;
1432 untracked_commit_option = 1;
1434 if (patch_mode) {
1435 ret = stash_patch(info, ps, patch, quiet);
1436 if (ret < 0) {
1437 if (!quiet)
1438 fprintf_ln(stderr, _("Cannot save the current "
1439 "worktree state"));
1440 goto done;
1441 } else if (ret > 0) {
1442 goto done;
1444 } else if (only_staged) {
1445 ret = stash_staged(info, patch, quiet);
1446 if (ret < 0) {
1447 if (!quiet)
1448 fprintf_ln(stderr, _("Cannot save the current "
1449 "staged state"));
1450 goto done;
1451 } else if (ret > 0) {
1452 goto done;
1454 } else {
1455 if (stash_working_tree(info, ps)) {
1456 if (!quiet)
1457 fprintf_ln(stderr, _("Cannot save the current "
1458 "worktree state"));
1459 ret = -1;
1460 goto done;
1464 if (!stash_msg_buf->len)
1465 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1466 else
1467 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1469 if (untracked_commit_option)
1470 commit_list_insert(lookup_commit(the_repository,
1471 &info->u_commit),
1472 &parents);
1473 commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1474 &parents);
1475 commit_list_insert(head_commit, &parents);
1477 if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1478 parents, &info->w_commit, NULL, NULL)) {
1479 if (!quiet)
1480 fprintf_ln(stderr, _("Cannot record "
1481 "working tree state"));
1482 ret = -1;
1483 goto done;
1486 done:
1487 strbuf_release(&commit_tree_label);
1488 strbuf_release(&msg);
1489 strbuf_release(&untracked_files);
1490 free_commit_list(parents);
1491 return ret;
1494 static int create_stash(int argc, const char **argv, const char *prefix UNUSED)
1496 int ret;
1497 struct strbuf stash_msg_buf = STRBUF_INIT;
1498 struct stash_info info = STASH_INFO_INIT;
1499 struct pathspec ps;
1501 /* Starting with argv[1], since argv[0] is "create" */
1502 strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
1504 memset(&ps, 0, sizeof(ps));
1505 if (!check_changes_tracked_files(&ps))
1506 return 0;
1508 ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, 0, &info,
1509 NULL, 0);
1510 if (!ret)
1511 printf_ln("%s", oid_to_hex(&info.w_commit));
1513 free_stash_info(&info);
1514 strbuf_release(&stash_msg_buf);
1515 return ret;
1518 static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int quiet,
1519 int keep_index, int patch_mode, int include_untracked, int only_staged)
1521 int ret = 0;
1522 struct stash_info info = STASH_INFO_INIT;
1523 struct strbuf patch = STRBUF_INIT;
1524 struct strbuf stash_msg_buf = STRBUF_INIT;
1525 struct strbuf untracked_files = STRBUF_INIT;
1526 struct strbuf out = STRBUF_INIT;
1528 if (patch_mode && keep_index == -1)
1529 keep_index = 1;
1531 if (patch_mode && include_untracked) {
1532 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1533 " or --all at the same time"));
1534 ret = -1;
1535 goto done;
1538 /* --patch overrides --staged */
1539 if (patch_mode)
1540 only_staged = 0;
1542 if (only_staged && include_untracked) {
1543 fprintf_ln(stderr, _("Can't use --staged and --include-untracked"
1544 " or --all at the same time"));
1545 ret = -1;
1546 goto done;
1549 repo_read_index_preload(the_repository, NULL, 0);
1550 if (!include_untracked && ps->nr) {
1551 int i;
1552 char *ps_matched = xcalloc(ps->nr, 1);
1554 /* TODO: audit for interaction with sparse-index. */
1555 ensure_full_index(the_repository->index);
1556 for (i = 0; i < the_repository->index->cache_nr; i++)
1557 ce_path_match(the_repository->index, the_repository->index->cache[i], ps,
1558 ps_matched);
1560 if (report_path_error(ps_matched, ps)) {
1561 fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1562 ret = -1;
1563 free(ps_matched);
1564 goto done;
1566 free(ps_matched);
1569 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1570 NULL, NULL, NULL)) {
1571 ret = error(_("could not write index"));
1572 goto done;
1575 if (!check_changes(ps, include_untracked, &untracked_files)) {
1576 if (!quiet)
1577 printf_ln(_("No local changes to save"));
1578 goto done;
1581 if (!refs_reflog_exists(get_main_ref_store(the_repository), ref_stash) && do_clear_stash()) {
1582 ret = -1;
1583 if (!quiet)
1584 fprintf_ln(stderr, _("Cannot initialize stash"));
1585 goto done;
1588 if (stash_msg)
1589 strbuf_addstr(&stash_msg_buf, stash_msg);
1590 if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode, only_staged,
1591 &info, &patch, quiet)) {
1592 ret = -1;
1593 goto done;
1596 if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1597 ret = -1;
1598 if (!quiet)
1599 fprintf_ln(stderr, _("Cannot save the current status"));
1600 goto done;
1603 if (!quiet)
1604 printf_ln(_("Saved working directory and index state %s"),
1605 stash_msg_buf.buf);
1607 if (!(patch_mode || only_staged)) {
1608 if (include_untracked && !ps->nr) {
1609 struct child_process cp = CHILD_PROCESS_INIT;
1611 cp.git_cmd = 1;
1612 if (startup_info->original_cwd) {
1613 cp.dir = startup_info->original_cwd;
1614 strvec_pushf(&cp.env, "%s=%s",
1615 GIT_WORK_TREE_ENVIRONMENT,
1616 the_repository->worktree);
1618 strvec_pushl(&cp.args, "clean", "--force",
1619 "--quiet", "-d", ":/", NULL);
1620 if (include_untracked == INCLUDE_ALL_FILES)
1621 strvec_push(&cp.args, "-x");
1622 if (run_command(&cp)) {
1623 ret = -1;
1624 goto done;
1627 discard_index(the_repository->index);
1628 if (ps->nr) {
1629 struct child_process cp_add = CHILD_PROCESS_INIT;
1630 struct child_process cp_diff = CHILD_PROCESS_INIT;
1631 struct child_process cp_apply = CHILD_PROCESS_INIT;
1633 cp_add.git_cmd = 1;
1634 strvec_push(&cp_add.args, "add");
1635 if (!include_untracked)
1636 strvec_push(&cp_add.args, "-u");
1637 if (include_untracked == INCLUDE_ALL_FILES)
1638 strvec_push(&cp_add.args, "--force");
1639 strvec_push(&cp_add.args, "--");
1640 add_pathspecs(&cp_add.args, ps);
1641 if (run_command(&cp_add)) {
1642 ret = -1;
1643 goto done;
1646 cp_diff.git_cmd = 1;
1647 strvec_pushl(&cp_diff.args, "diff-index", "-p",
1648 "--cached", "--binary", "HEAD", "--",
1649 NULL);
1650 add_pathspecs(&cp_diff.args, ps);
1651 if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1652 ret = -1;
1653 goto done;
1656 cp_apply.git_cmd = 1;
1657 strvec_pushl(&cp_apply.args, "apply", "--index",
1658 "-R", NULL);
1659 if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1660 NULL, 0)) {
1661 ret = -1;
1662 goto done;
1664 } else {
1665 struct child_process cp = CHILD_PROCESS_INIT;
1666 cp.git_cmd = 1;
1667 /* BUG: this nukes untracked files in the way */
1668 strvec_pushl(&cp.args, "reset", "--hard", "-q",
1669 "--no-recurse-submodules", NULL);
1670 if (run_command(&cp)) {
1671 ret = -1;
1672 goto done;
1677 * When keeping staged entries, we need to reset the working
1678 * directory to match the state of our index. This can be
1679 * skipped when the index is the empty tree, because there is
1680 * nothing to reset in that case:
1682 * - When the index has any file, regardless of whether
1683 * staged or not, the tree cannot be empty by definition
1684 * and thus we enter the condition.
1686 * - When the index has no files, the only thing we need to
1687 * care about is untracked files when `--include-untracked`
1688 * is given. But as we already execute git-clean(1) further
1689 * up to delete such untracked files we don't have to do
1690 * anything here, either.
1692 * We thus skip calling git-checkout(1) in this case, also
1693 * because running it on an empty tree will cause it to fail
1694 * due to the pathspec not matching anything.
1696 if (keep_index == 1 && !is_null_oid(&info.i_tree) &&
1697 !is_empty_tree_oid(&info.i_tree, the_repository->hash_algo)) {
1698 struct child_process cp = CHILD_PROCESS_INIT;
1700 cp.git_cmd = 1;
1701 strvec_pushl(&cp.args, "checkout", "--no-overlay",
1702 oid_to_hex(&info.i_tree), "--", NULL);
1703 if (!ps->nr)
1704 strvec_push(&cp.args, ":/");
1705 else
1706 add_pathspecs(&cp.args, ps);
1707 if (run_command(&cp)) {
1708 ret = -1;
1709 goto done;
1712 goto done;
1713 } else {
1714 struct child_process cp = CHILD_PROCESS_INIT;
1716 cp.git_cmd = 1;
1717 strvec_pushl(&cp.args, "apply", "-R", NULL);
1719 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1720 if (!quiet)
1721 fprintf_ln(stderr, _("Cannot remove "
1722 "worktree changes"));
1723 ret = -1;
1724 goto done;
1727 if (keep_index < 1) {
1728 struct child_process cp = CHILD_PROCESS_INIT;
1730 cp.git_cmd = 1;
1731 strvec_pushl(&cp.args, "reset", "-q", "--refresh", "--",
1732 NULL);
1733 add_pathspecs(&cp.args, ps);
1734 if (run_command(&cp)) {
1735 ret = -1;
1736 goto done;
1739 goto done;
1742 done:
1743 strbuf_release(&patch);
1744 strbuf_release(&out);
1745 free_stash_info(&info);
1746 strbuf_release(&stash_msg_buf);
1747 strbuf_release(&untracked_files);
1748 return ret;
1751 static int push_stash(int argc, const char **argv, const char *prefix,
1752 int push_assumed)
1754 int force_assume = 0;
1755 int keep_index = -1;
1756 int only_staged = 0;
1757 int patch_mode = 0;
1758 int include_untracked = 0;
1759 int quiet = 0;
1760 int pathspec_file_nul = 0;
1761 const char *stash_msg = NULL;
1762 char *pathspec_from_file = NULL;
1763 struct pathspec ps;
1764 struct option options[] = {
1765 OPT_BOOL('k', "keep-index", &keep_index,
1766 N_("keep index")),
1767 OPT_BOOL('S', "staged", &only_staged,
1768 N_("stash staged changes only")),
1769 OPT_BOOL('p', "patch", &patch_mode,
1770 N_("stash in patch mode")),
1771 OPT__QUIET(&quiet, N_("quiet mode")),
1772 OPT_BOOL('u', "include-untracked", &include_untracked,
1773 N_("include untracked files in stash")),
1774 OPT_SET_INT('a', "all", &include_untracked,
1775 N_("include ignore files"), 2),
1776 OPT_STRING('m', "message", &stash_msg, N_("message"),
1777 N_("stash message")),
1778 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1779 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1780 OPT_END()
1782 int ret;
1784 if (argc) {
1785 force_assume = !strcmp(argv[0], "-p");
1786 argc = parse_options(argc, argv, prefix, options,
1787 push_assumed ? git_stash_usage :
1788 git_stash_push_usage,
1789 PARSE_OPT_KEEP_DASHDASH);
1792 if (argc) {
1793 if (!strcmp(argv[0], "--")) {
1794 argc--;
1795 argv++;
1796 } else if (push_assumed && !force_assume) {
1797 die("subcommand wasn't specified; 'push' can't be assumed due to unexpected token '%s'",
1798 argv[0]);
1802 parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1803 prefix, argv);
1805 if (pathspec_from_file) {
1806 if (patch_mode)
1807 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1809 if (only_staged)
1810 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--staged");
1812 if (ps.nr)
1813 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1815 parse_pathspec_file(&ps, 0,
1816 PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1817 prefix, pathspec_from_file, pathspec_file_nul);
1818 } else if (pathspec_file_nul) {
1819 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1822 ret = do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
1823 include_untracked, only_staged);
1825 clear_pathspec(&ps);
1826 free(pathspec_from_file);
1827 return ret;
1830 static int push_stash_unassumed(int argc, const char **argv, const char *prefix)
1832 return push_stash(argc, argv, prefix, 0);
1835 static int save_stash(int argc, const char **argv, const char *prefix)
1837 int keep_index = -1;
1838 int only_staged = 0;
1839 int patch_mode = 0;
1840 int include_untracked = 0;
1841 int quiet = 0;
1842 int ret = 0;
1843 const char *stash_msg = NULL;
1844 struct pathspec ps;
1845 struct strbuf stash_msg_buf = STRBUF_INIT;
1846 struct option options[] = {
1847 OPT_BOOL('k', "keep-index", &keep_index,
1848 N_("keep index")),
1849 OPT_BOOL('S', "staged", &only_staged,
1850 N_("stash staged changes only")),
1851 OPT_BOOL('p', "patch", &patch_mode,
1852 N_("stash in patch mode")),
1853 OPT__QUIET(&quiet, N_("quiet mode")),
1854 OPT_BOOL('u', "include-untracked", &include_untracked,
1855 N_("include untracked files in stash")),
1856 OPT_SET_INT('a', "all", &include_untracked,
1857 N_("include ignore files"), 2),
1858 OPT_STRING('m', "message", &stash_msg, "message",
1859 N_("stash message")),
1860 OPT_END()
1863 argc = parse_options(argc, argv, prefix, options,
1864 git_stash_save_usage,
1865 PARSE_OPT_KEEP_DASHDASH);
1867 if (argc)
1868 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
1870 memset(&ps, 0, sizeof(ps));
1871 ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
1872 patch_mode, include_untracked, only_staged);
1874 strbuf_release(&stash_msg_buf);
1875 return ret;
1878 int cmd_stash(int argc,
1879 const char **argv,
1880 const char *prefix,
1881 struct repository *repo UNUSED)
1883 pid_t pid = getpid();
1884 const char *index_file;
1885 struct strvec args = STRVEC_INIT;
1886 parse_opt_subcommand_fn *fn = NULL;
1887 struct option options[] = {
1888 OPT_SUBCOMMAND("apply", &fn, apply_stash),
1889 OPT_SUBCOMMAND("clear", &fn, clear_stash),
1890 OPT_SUBCOMMAND("drop", &fn, drop_stash),
1891 OPT_SUBCOMMAND("pop", &fn, pop_stash),
1892 OPT_SUBCOMMAND("branch", &fn, branch_stash),
1893 OPT_SUBCOMMAND("list", &fn, list_stash),
1894 OPT_SUBCOMMAND("show", &fn, show_stash),
1895 OPT_SUBCOMMAND("store", &fn, store_stash),
1896 OPT_SUBCOMMAND("create", &fn, create_stash),
1897 OPT_SUBCOMMAND("push", &fn, push_stash_unassumed),
1898 OPT_SUBCOMMAND_F("save", &fn, save_stash, PARSE_OPT_NOCOMPLETE),
1899 OPT_END()
1901 const char **args_copy;
1902 int ret;
1904 git_config(git_stash_config, NULL);
1906 argc = parse_options(argc, argv, prefix, options, git_stash_usage,
1907 PARSE_OPT_SUBCOMMAND_OPTIONAL |
1908 PARSE_OPT_KEEP_UNKNOWN_OPT |
1909 PARSE_OPT_KEEP_DASHDASH);
1911 prepare_repo_settings(the_repository);
1912 the_repository->settings.command_requires_full_index = 0;
1914 index_file = repo_get_index_file(the_repository);
1915 strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
1916 (uintmax_t)pid);
1918 if (fn)
1919 return !!fn(argc, argv, prefix);
1920 else if (!argc)
1921 return !!push_stash_unassumed(0, NULL, prefix);
1923 /* Assume 'stash push' */
1924 strvec_push(&args, "push");
1925 strvec_pushv(&args, argv);
1928 * `push_stash()` ends up modifying the array, which causes memory
1929 * leaks if we didn't copy the array here.
1931 DUP_ARRAY(args_copy, args.v, args.nr);
1933 ret = !!push_stash(args.nr, args_copy, prefix, 1);
1935 strvec_clear(&args);
1936 free(args_copy);
1937 return ret;