midx: bounds-check large offset chunk
[git.git] / builtin / stash.c
blob1ad496985ab196e4d40e394843480c9341f72e6d
1 #define USE_THE_INDEX_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 "rerere.h"
24 #include "revision.h"
25 #include "setup.h"
26 #include "sparse-index.h"
27 #include "log-tree.h"
28 #include "diffcore.h"
29 #include "exec-cmd.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 (!ref_exists(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 delete_ref(NULL, ref_stash, &obj, 0);
251 static int clear_stash(int argc, const char **argv, const char *prefix)
253 struct option options[] = {
254 OPT_END()
257 argc = parse_options(argc, argv, prefix, options,
258 git_stash_clear_usage,
259 PARSE_OPT_STOP_AT_NON_OPTION);
261 if (argc)
262 return error(_("git stash clear with arguments is "
263 "unimplemented"));
265 return do_clear_stash();
268 static int reset_tree(struct object_id *i_tree, int update, int reset)
270 int nr_trees = 1;
271 struct unpack_trees_options opts;
272 struct tree_desc t[MAX_UNPACK_TREES];
273 struct tree *tree;
274 struct lock_file lock_file = LOCK_INIT;
276 repo_read_index_preload(the_repository, NULL, 0);
277 if (refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL))
278 return -1;
280 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
282 memset(&opts, 0, sizeof(opts));
284 tree = parse_tree_indirect(i_tree);
285 if (parse_tree(tree))
286 return -1;
288 init_tree_desc(t, tree->buffer, tree->size);
290 opts.head_idx = 1;
291 opts.src_index = &the_index;
292 opts.dst_index = &the_index;
293 opts.merge = 1;
294 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
295 opts.update = update;
296 if (update)
297 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
298 opts.fn = oneway_merge;
300 if (unpack_trees(nr_trees, t, &opts))
301 return -1;
303 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
304 return error(_("unable to write new index file"));
306 return 0;
309 static int diff_tree_binary(struct strbuf *out, struct object_id *w_commit)
311 struct child_process cp = CHILD_PROCESS_INIT;
312 const char *w_commit_hex = oid_to_hex(w_commit);
315 * Diff-tree would not be very hard to replace with a native function,
316 * however it should be done together with apply_cached.
318 cp.git_cmd = 1;
319 strvec_pushl(&cp.args, "diff-tree", "--binary", NULL);
320 strvec_pushf(&cp.args, "%s^2^..%s^2", w_commit_hex, w_commit_hex);
322 return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
325 static int apply_cached(struct strbuf *out)
327 struct child_process cp = CHILD_PROCESS_INIT;
330 * Apply currently only reads either from stdin or a file, thus
331 * apply_all_patches would have to be updated to optionally take a
332 * buffer.
334 cp.git_cmd = 1;
335 strvec_pushl(&cp.args, "apply", "--cached", NULL);
336 return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
339 static int reset_head(void)
341 struct child_process cp = CHILD_PROCESS_INIT;
344 * Reset is overall quite simple, however there is no current public
345 * API for resetting.
347 cp.git_cmd = 1;
348 strvec_pushl(&cp.args, "reset", "--quiet", "--refresh", NULL);
350 return run_command(&cp);
353 static int is_path_a_directory(const char *path)
356 * This function differs from abspath.c:is_directory() in that
357 * here we use lstat() instead of stat(); we do not want to
358 * follow symbolic links here.
360 struct stat st;
361 return (!lstat(path, &st) && S_ISDIR(st.st_mode));
364 static void add_diff_to_buf(struct diff_queue_struct *q,
365 struct diff_options *options UNUSED,
366 void *data)
368 int i;
370 for (i = 0; i < q->nr; i++) {
371 if (is_path_a_directory(q->queue[i]->one->path))
372 continue;
374 strbuf_addstr(data, q->queue[i]->one->path);
376 /* NUL-terminate: will be fed to update-index -z */
377 strbuf_addch(data, '\0');
381 static int restore_untracked(struct object_id *u_tree)
383 int res;
384 struct child_process cp = CHILD_PROCESS_INIT;
387 * We need to run restore files from a given index, but without
388 * affecting the current index, so we use GIT_INDEX_FILE with
389 * run_command to fork processes that will not interfere.
391 cp.git_cmd = 1;
392 strvec_push(&cp.args, "read-tree");
393 strvec_push(&cp.args, oid_to_hex(u_tree));
394 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
395 stash_index_path.buf);
396 if (run_command(&cp)) {
397 remove_path(stash_index_path.buf);
398 return -1;
401 child_process_init(&cp);
402 cp.git_cmd = 1;
403 strvec_pushl(&cp.args, "checkout-index", "--all", NULL);
404 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
405 stash_index_path.buf);
407 res = run_command(&cp);
408 remove_path(stash_index_path.buf);
409 return res;
412 static void unstage_changes_unless_new(struct object_id *orig_tree)
415 * When we enter this function, there has been a clean merge of
416 * relevant trees, and the merge logic always stages whatever merges
417 * cleanly. We want to unstage those changes, unless it corresponds
418 * to a file that didn't exist as of orig_tree.
420 * However, if any SKIP_WORKTREE path is modified relative to
421 * orig_tree, then we want to clear the SKIP_WORKTREE bit and write
422 * it to the worktree before unstaging.
425 struct checkout state = CHECKOUT_INIT;
426 struct diff_options diff_opts;
427 struct lock_file lock = LOCK_INIT;
428 int i;
430 /* If any entries have skip_worktree set, we'll have to check 'em out */
431 state.force = 1;
432 state.quiet = 1;
433 state.refresh_cache = 1;
434 state.istate = &the_index;
437 * Step 1: get a difference between orig_tree (which corresponding
438 * to the index before a merge was run) and the current index
439 * (reflecting the changes brought in by the merge).
441 repo_diff_setup(the_repository, &diff_opts);
442 diff_opts.flags.recursive = 1;
443 diff_opts.detect_rename = 0;
444 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
445 diff_setup_done(&diff_opts);
447 do_diff_cache(orig_tree, &diff_opts);
448 diffcore_std(&diff_opts);
450 /* Iterate over the paths that changed due to the merge... */
451 for (i = 0; i < diff_queued_diff.nr; i++) {
452 struct diff_filepair *p;
453 struct cache_entry *ce;
454 int pos;
456 /* Look up the path's position in the current index. */
457 p = diff_queued_diff.queue[i];
458 pos = index_name_pos(&the_index, p->two->path,
459 strlen(p->two->path));
462 * Step 2: Place changes in the working tree
464 * Stash is about restoring changes *to the working tree*.
465 * So if the merge successfully got a new version of some
466 * path, but left it out of the working tree, then clear the
467 * SKIP_WORKTREE bit and write it to the working tree.
469 if (pos >= 0 && ce_skip_worktree(the_index.cache[pos])) {
470 struct stat st;
472 ce = the_index.cache[pos];
473 if (!lstat(ce->name, &st)) {
474 /* Conflicting path present; relocate it */
475 struct strbuf new_path = STRBUF_INIT;
476 int fd;
478 strbuf_addf(&new_path,
479 "%s.stash.XXXXXX", ce->name);
480 fd = xmkstemp(new_path.buf);
481 close(fd);
482 printf(_("WARNING: Untracked file in way of "
483 "tracked file! Renaming\n "
484 " %s -> %s\n"
485 " to make room.\n"),
486 ce->name, new_path.buf);
487 if (rename(ce->name, new_path.buf))
488 die("Failed to move %s to %s\n",
489 ce->name, new_path.buf);
490 strbuf_release(&new_path);
492 checkout_entry(ce, &state, NULL, NULL);
493 ce->ce_flags &= ~CE_SKIP_WORKTREE;
497 * Step 3: "unstage" changes, as long as they are still tracked
499 if (p->one->oid_valid) {
501 * Path existed in orig_tree; restore index entry
502 * from that tree in order to "unstage" the changes.
504 int option = ADD_CACHE_OK_TO_REPLACE;
505 if (pos < 0)
506 option = ADD_CACHE_OK_TO_ADD;
508 ce = make_cache_entry(&the_index,
509 p->one->mode,
510 &p->one->oid,
511 p->one->path,
512 0, 0);
513 add_index_entry(&the_index, ce, option);
516 diff_flush(&diff_opts);
519 * Step 4: write the new index to disk
521 repo_hold_locked_index(the_repository, &lock, LOCK_DIE_ON_ERROR);
522 if (write_locked_index(&the_index, &lock,
523 COMMIT_LOCK | SKIP_IF_UNCHANGED))
524 die(_("Unable to write index."));
527 static int do_apply_stash(const char *prefix, struct stash_info *info,
528 int index, int quiet)
530 int clean, ret;
531 int has_index = index;
532 struct merge_options o;
533 struct object_id c_tree;
534 struct object_id index_tree;
535 struct tree *head, *merge, *merge_base;
536 struct lock_file lock = LOCK_INIT;
538 repo_read_index_preload(the_repository, NULL, 0);
539 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
540 NULL, NULL, NULL))
541 return -1;
543 if (write_index_as_tree(&c_tree, &the_index, get_index_file(), 0,
544 NULL))
545 return error(_("cannot apply a stash in the middle of a merge"));
547 if (index) {
548 if (oideq(&info->b_tree, &info->i_tree) ||
549 oideq(&c_tree, &info->i_tree)) {
550 has_index = 0;
551 } else {
552 struct strbuf out = STRBUF_INIT;
554 if (diff_tree_binary(&out, &info->w_commit)) {
555 strbuf_release(&out);
556 return error(_("could not generate diff %s^!."),
557 oid_to_hex(&info->w_commit));
560 ret = apply_cached(&out);
561 strbuf_release(&out);
562 if (ret)
563 return error(_("conflicts in index. "
564 "Try without --index."));
566 discard_index(&the_index);
567 repo_read_index(the_repository);
568 if (write_index_as_tree(&index_tree, &the_index,
569 get_index_file(), 0, NULL))
570 return error(_("could not save index tree"));
572 reset_head();
573 discard_index(&the_index);
574 repo_read_index(the_repository);
578 init_merge_options(&o, the_repository);
580 o.branch1 = "Updated upstream";
581 o.branch2 = "Stashed changes";
582 o.ancestor = "Stash base";
584 if (oideq(&info->b_tree, &c_tree))
585 o.branch1 = "Version stash was based on";
587 if (quiet)
588 o.verbosity = 0;
590 if (o.verbosity >= 3)
591 printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
593 head = lookup_tree(o.repo, &c_tree);
594 merge = lookup_tree(o.repo, &info->w_tree);
595 merge_base = lookup_tree(o.repo, &info->b_tree);
597 repo_hold_locked_index(o.repo, &lock, LOCK_DIE_ON_ERROR);
598 clean = merge_ort_nonrecursive(&o, head, merge, merge_base);
601 * If 'clean' >= 0, reverse the value for 'ret' so 'ret' is 0 when the
602 * merge was clean, and nonzero if the merge was unclean or encountered
603 * an error.
605 ret = clean >= 0 ? !clean : clean;
607 if (ret < 0)
608 rollback_lock_file(&lock);
609 else if (write_locked_index(o.repo->index, &lock,
610 COMMIT_LOCK | SKIP_IF_UNCHANGED))
611 ret = error(_("could not write index"));
613 if (ret) {
614 repo_rerere(the_repository, 0);
616 if (index)
617 fprintf_ln(stderr, _("Index was not unstashed."));
619 goto restore_untracked;
622 if (has_index) {
623 if (reset_tree(&index_tree, 0, 0))
624 ret = -1;
625 } else {
626 unstage_changes_unless_new(&c_tree);
629 restore_untracked:
630 if (info->has_u && restore_untracked(&info->u_tree))
631 ret = error(_("could not restore untracked files from stash"));
633 if (!quiet) {
634 struct child_process cp = CHILD_PROCESS_INIT;
637 * Status is quite simple and could be replaced with calls to
638 * wt_status in the future, but it adds complexities which may
639 * require more tests.
641 cp.git_cmd = 1;
642 cp.dir = prefix;
643 strvec_pushf(&cp.env, GIT_WORK_TREE_ENVIRONMENT"=%s",
644 absolute_path(get_git_work_tree()));
645 strvec_pushf(&cp.env, GIT_DIR_ENVIRONMENT"=%s",
646 absolute_path(get_git_dir()));
647 strvec_push(&cp.args, "status");
648 run_command(&cp);
651 return ret;
654 static int apply_stash(int argc, const char **argv, const char *prefix)
656 int ret = -1;
657 int quiet = 0;
658 int index = 0;
659 struct stash_info info = STASH_INFO_INIT;
660 struct option options[] = {
661 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
662 OPT_BOOL(0, "index", &index,
663 N_("attempt to recreate the index")),
664 OPT_END()
667 argc = parse_options(argc, argv, prefix, options,
668 git_stash_apply_usage, 0);
670 if (get_stash_info(&info, argc, argv))
671 goto cleanup;
673 ret = do_apply_stash(prefix, &info, index, quiet);
674 cleanup:
675 free_stash_info(&info);
676 return ret;
679 static int reject_reflog_ent(struct object_id *ooid UNUSED,
680 struct object_id *noid UNUSED,
681 const char *email UNUSED,
682 timestamp_t timestamp UNUSED,
683 int tz UNUSED, const char *message UNUSED,
684 void *cb_data UNUSED)
686 return 1;
689 static int reflog_is_empty(const char *refname)
691 return !for_each_reflog_ent(refname, reject_reflog_ent, NULL);
694 static int do_drop_stash(struct stash_info *info, int quiet)
696 if (!reflog_delete(info->revision.buf,
697 EXPIRE_REFLOGS_REWRITE | EXPIRE_REFLOGS_UPDATE_REF,
698 0)) {
699 if (!quiet)
700 printf_ln(_("Dropped %s (%s)"), info->revision.buf,
701 oid_to_hex(&info->w_commit));
702 } else {
703 return error(_("%s: Could not drop stash entry"),
704 info->revision.buf);
707 if (reflog_is_empty(ref_stash))
708 do_clear_stash();
710 return 0;
713 static int get_stash_info_assert(struct stash_info *info, int argc,
714 const char **argv)
716 int ret = get_stash_info(info, argc, argv);
718 if (ret < 0)
719 return ret;
721 if (!info->is_stash_ref)
722 return error(_("'%s' is not a stash reference"), info->revision.buf);
724 return 0;
727 static int drop_stash(int argc, const char **argv, const char *prefix)
729 int ret = -1;
730 int quiet = 0;
731 struct stash_info info = STASH_INFO_INIT;
732 struct option options[] = {
733 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
734 OPT_END()
737 argc = parse_options(argc, argv, prefix, options,
738 git_stash_drop_usage, 0);
740 if (get_stash_info_assert(&info, argc, argv))
741 goto cleanup;
743 ret = do_drop_stash(&info, quiet);
744 cleanup:
745 free_stash_info(&info);
746 return ret;
749 static int pop_stash(int argc, const char **argv, const char *prefix)
751 int ret = -1;
752 int index = 0;
753 int quiet = 0;
754 struct stash_info info = STASH_INFO_INIT;
755 struct option options[] = {
756 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
757 OPT_BOOL(0, "index", &index,
758 N_("attempt to recreate the index")),
759 OPT_END()
762 argc = parse_options(argc, argv, prefix, options,
763 git_stash_pop_usage, 0);
765 if (get_stash_info_assert(&info, argc, argv))
766 goto cleanup;
768 if ((ret = do_apply_stash(prefix, &info, index, quiet)))
769 printf_ln(_("The stash entry is kept in case "
770 "you need it again."));
771 else
772 ret = do_drop_stash(&info, quiet);
774 cleanup:
775 free_stash_info(&info);
776 return ret;
779 static int branch_stash(int argc, const char **argv, const char *prefix)
781 int ret = -1;
782 const char *branch = NULL;
783 struct stash_info info = STASH_INFO_INIT;
784 struct child_process cp = CHILD_PROCESS_INIT;
785 struct option options[] = {
786 OPT_END()
789 argc = parse_options(argc, argv, prefix, options,
790 git_stash_branch_usage, 0);
792 if (!argc) {
793 fprintf_ln(stderr, _("No branch name specified"));
794 return -1;
797 branch = argv[0];
799 if (get_stash_info(&info, argc - 1, argv + 1))
800 goto cleanup;
802 cp.git_cmd = 1;
803 strvec_pushl(&cp.args, "checkout", "-b", NULL);
804 strvec_push(&cp.args, branch);
805 strvec_push(&cp.args, oid_to_hex(&info.b_commit));
806 ret = run_command(&cp);
807 if (!ret)
808 ret = do_apply_stash(prefix, &info, 1, 0);
809 if (!ret && info.is_stash_ref)
810 ret = do_drop_stash(&info, 0);
812 cleanup:
813 free_stash_info(&info);
814 return ret;
817 static int list_stash(int argc, const char **argv, const char *prefix)
819 struct child_process cp = CHILD_PROCESS_INIT;
820 struct option options[] = {
821 OPT_END()
824 argc = parse_options(argc, argv, prefix, options,
825 git_stash_list_usage,
826 PARSE_OPT_KEEP_UNKNOWN_OPT);
828 if (!ref_exists(ref_stash))
829 return 0;
831 cp.git_cmd = 1;
832 strvec_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
833 "--first-parent", NULL);
834 strvec_pushv(&cp.args, argv);
835 strvec_push(&cp.args, ref_stash);
836 strvec_push(&cp.args, "--");
837 return run_command(&cp);
840 static int show_stat = 1;
841 static int show_patch;
842 static int show_include_untracked;
844 static int git_stash_config(const char *var, const char *value,
845 const struct config_context *ctx, void *cb)
847 if (!strcmp(var, "stash.showstat")) {
848 show_stat = git_config_bool(var, value);
849 return 0;
851 if (!strcmp(var, "stash.showpatch")) {
852 show_patch = git_config_bool(var, value);
853 return 0;
855 if (!strcmp(var, "stash.showincludeuntracked")) {
856 show_include_untracked = git_config_bool(var, value);
857 return 0;
859 return git_diff_basic_config(var, value, ctx, cb);
862 static void diff_include_untracked(const struct stash_info *info, struct diff_options *diff_opt)
864 const struct object_id *oid[] = { &info->w_commit, &info->u_tree };
865 struct tree *tree[ARRAY_SIZE(oid)];
866 struct tree_desc tree_desc[ARRAY_SIZE(oid)];
867 struct unpack_trees_options unpack_tree_opt = { 0 };
868 int i;
870 for (i = 0; i < ARRAY_SIZE(oid); i++) {
871 tree[i] = parse_tree_indirect(oid[i]);
872 if (parse_tree(tree[i]) < 0)
873 die(_("failed to parse tree"));
874 init_tree_desc(&tree_desc[i], tree[i]->buffer, tree[i]->size);
877 unpack_tree_opt.head_idx = -1;
878 unpack_tree_opt.src_index = &the_index;
879 unpack_tree_opt.dst_index = &the_index;
880 unpack_tree_opt.merge = 1;
881 unpack_tree_opt.fn = stash_worktree_untracked_merge;
883 if (unpack_trees(ARRAY_SIZE(tree_desc), tree_desc, &unpack_tree_opt))
884 die(_("failed to unpack trees"));
886 do_diff_cache(&info->b_commit, diff_opt);
889 static int show_stash(int argc, const char **argv, const char *prefix)
891 int i;
892 int ret = -1;
893 struct stash_info info = STASH_INFO_INIT;
894 struct rev_info rev;
895 struct strvec stash_args = STRVEC_INIT;
896 struct strvec revision_args = STRVEC_INIT;
897 enum {
898 UNTRACKED_NONE,
899 UNTRACKED_INCLUDE,
900 UNTRACKED_ONLY
901 } show_untracked = show_include_untracked ? UNTRACKED_INCLUDE : UNTRACKED_NONE;
902 struct option options[] = {
903 OPT_SET_INT('u', "include-untracked", &show_untracked,
904 N_("include untracked files in the stash"),
905 UNTRACKED_INCLUDE),
906 OPT_SET_INT_F(0, "only-untracked", &show_untracked,
907 N_("only show untracked files in the stash"),
908 UNTRACKED_ONLY, PARSE_OPT_NONEG),
909 OPT_END()
911 int do_usage = 0;
913 init_diff_ui_defaults();
914 git_config(git_diff_ui_config, NULL);
915 repo_init_revisions(the_repository, &rev, prefix);
917 argc = parse_options(argc, argv, prefix, options, git_stash_show_usage,
918 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
919 PARSE_OPT_KEEP_DASHDASH);
921 strvec_push(&revision_args, argv[0]);
922 for (i = 1; i < argc; i++) {
923 if (argv[i][0] != '-')
924 strvec_push(&stash_args, argv[i]);
925 else
926 strvec_push(&revision_args, argv[i]);
929 if (get_stash_info(&info, stash_args.nr, stash_args.v))
930 goto cleanup;
933 * The config settings are applied only if there are not passed
934 * any options.
936 if (revision_args.nr == 1) {
937 if (show_stat)
938 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
940 if (show_patch)
941 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
943 if (!show_stat && !show_patch) {
944 ret = 0;
945 goto cleanup;
949 argc = setup_revisions(revision_args.nr, revision_args.v, &rev, NULL);
950 if (argc > 1)
951 goto usage;
952 if (!rev.diffopt.output_format) {
953 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
954 diff_setup_done(&rev.diffopt);
957 rev.diffopt.flags.recursive = 1;
958 setup_diff_pager(&rev.diffopt);
959 switch (show_untracked) {
960 case UNTRACKED_NONE:
961 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
962 break;
963 case UNTRACKED_ONLY:
964 if (info.has_u)
965 diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
966 break;
967 case UNTRACKED_INCLUDE:
968 if (info.has_u)
969 diff_include_untracked(&info, &rev.diffopt);
970 else
971 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
972 break;
974 log_tree_diff_flush(&rev);
976 ret = diff_result_code(&rev.diffopt);
977 cleanup:
978 strvec_clear(&stash_args);
979 free_stash_info(&info);
980 release_revisions(&rev);
981 if (do_usage)
982 usage_with_options(git_stash_show_usage, options);
983 return ret;
984 usage:
985 do_usage = 1;
986 goto cleanup;
989 static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
990 int quiet)
992 if (!stash_msg)
993 stash_msg = "Created via \"git stash store\".";
995 if (update_ref(stash_msg, ref_stash, w_commit, NULL,
996 REF_FORCE_CREATE_REFLOG,
997 quiet ? UPDATE_REFS_QUIET_ON_ERR :
998 UPDATE_REFS_MSG_ON_ERR)) {
999 if (!quiet) {
1000 fprintf_ln(stderr, _("Cannot update %s with %s"),
1001 ref_stash, oid_to_hex(w_commit));
1003 return -1;
1006 return 0;
1009 static int store_stash(int argc, const char **argv, const char *prefix)
1011 int quiet = 0;
1012 const char *stash_msg = NULL;
1013 struct object_id obj;
1014 struct object_context dummy;
1015 struct option options[] = {
1016 OPT__QUIET(&quiet, N_("be quiet")),
1017 OPT_STRING('m', "message", &stash_msg, "message",
1018 N_("stash message")),
1019 OPT_END()
1022 argc = parse_options(argc, argv, prefix, options,
1023 git_stash_store_usage,
1024 PARSE_OPT_KEEP_UNKNOWN_OPT);
1026 if (argc != 1) {
1027 if (!quiet)
1028 fprintf_ln(stderr, _("\"git stash store\" requires one "
1029 "<commit> argument"));
1030 return -1;
1033 if (get_oid_with_context(the_repository,
1034 argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
1035 &dummy)) {
1036 if (!quiet)
1037 fprintf_ln(stderr, _("Cannot update %s with %s"),
1038 ref_stash, argv[0]);
1039 return -1;
1042 return do_store_stash(&obj, stash_msg, quiet);
1045 static void add_pathspecs(struct strvec *args,
1046 const struct pathspec *ps) {
1047 int i;
1049 for (i = 0; i < ps->nr; i++)
1050 strvec_push(args, ps->items[i].original);
1054 * `untracked_files` will be filled with the names of untracked files.
1055 * The return value is:
1057 * = 0 if there are not any untracked files
1058 * > 0 if there are untracked files
1060 static int get_untracked_files(const struct pathspec *ps, int include_untracked,
1061 struct strbuf *untracked_files)
1063 int i;
1064 int found = 0;
1065 struct dir_struct dir = DIR_INIT;
1067 if (include_untracked != INCLUDE_ALL_FILES)
1068 setup_standard_excludes(&dir);
1070 fill_directory(&dir, the_repository->index, ps);
1071 for (i = 0; i < dir.nr; i++) {
1072 struct dir_entry *ent = dir.entries[i];
1073 found++;
1074 strbuf_addstr(untracked_files, ent->name);
1075 /* NUL-terminate: will be fed to update-index -z */
1076 strbuf_addch(untracked_files, '\0');
1079 dir_clear(&dir);
1080 return found;
1084 * The return value of `check_changes_tracked_files()` can be:
1086 * < 0 if there was an error
1087 * = 0 if there are no changes.
1088 * > 0 if there are changes.
1090 static int check_changes_tracked_files(const struct pathspec *ps)
1092 struct rev_info rev;
1093 struct object_id dummy;
1094 int ret = 0;
1096 /* No initial commit. */
1097 if (repo_get_oid(the_repository, "HEAD", &dummy))
1098 return -1;
1100 if (repo_read_index(the_repository) < 0)
1101 return -1;
1103 repo_init_revisions(the_repository, &rev, NULL);
1104 copy_pathspec(&rev.prune_data, ps);
1106 rev.diffopt.flags.quick = 1;
1107 rev.diffopt.flags.ignore_submodules = 1;
1108 rev.abbrev = 0;
1110 add_head_to_pending(&rev);
1111 diff_setup_done(&rev.diffopt);
1113 run_diff_index(&rev, DIFF_INDEX_CACHED);
1114 if (diff_result_code(&rev.diffopt)) {
1115 ret = 1;
1116 goto done;
1119 run_diff_files(&rev, 0);
1120 if (diff_result_code(&rev.diffopt)) {
1121 ret = 1;
1122 goto done;
1125 done:
1126 release_revisions(&rev);
1127 return ret;
1131 * The function will fill `untracked_files` with the names of untracked files
1132 * It will return 1 if there were any changes and 0 if there were not.
1134 static int check_changes(const struct pathspec *ps, int include_untracked,
1135 struct strbuf *untracked_files)
1137 int ret = 0;
1138 if (check_changes_tracked_files(ps))
1139 ret = 1;
1141 if (include_untracked && get_untracked_files(ps, include_untracked,
1142 untracked_files))
1143 ret = 1;
1145 return ret;
1148 static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
1149 struct strbuf files)
1151 int ret = 0;
1152 struct strbuf untracked_msg = STRBUF_INIT;
1153 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1154 struct index_state istate = INDEX_STATE_INIT(the_repository);
1156 cp_upd_index.git_cmd = 1;
1157 strvec_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
1158 "--remove", "--stdin", NULL);
1159 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1160 stash_index_path.buf);
1162 strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
1163 if (pipe_command(&cp_upd_index, files.buf, files.len, NULL, 0,
1164 NULL, 0)) {
1165 ret = -1;
1166 goto done;
1169 if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
1170 NULL)) {
1171 ret = -1;
1172 goto done;
1175 if (commit_tree(untracked_msg.buf, untracked_msg.len,
1176 &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
1177 ret = -1;
1178 goto done;
1181 done:
1182 release_index(&istate);
1183 strbuf_release(&untracked_msg);
1184 remove_path(stash_index_path.buf);
1185 return ret;
1188 static int stash_staged(struct stash_info *info, struct strbuf *out_patch,
1189 int quiet)
1191 int ret = 0;
1192 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1193 struct index_state istate = INDEX_STATE_INIT(the_repository);
1195 if (write_index_as_tree(&info->w_tree, &istate, the_repository->index_file,
1196 0, NULL)) {
1197 ret = -1;
1198 goto done;
1201 cp_diff_tree.git_cmd = 1;
1202 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1203 oid_to_hex(&info->w_tree), "--", NULL);
1204 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1205 ret = -1;
1206 goto done;
1209 if (!out_patch->len) {
1210 if (!quiet)
1211 fprintf_ln(stderr, _("No staged changes"));
1212 ret = 1;
1215 done:
1216 release_index(&istate);
1217 return ret;
1220 static int stash_patch(struct stash_info *info, const struct pathspec *ps,
1221 struct strbuf *out_patch, int quiet)
1223 int ret = 0;
1224 struct child_process cp_read_tree = CHILD_PROCESS_INIT;
1225 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1226 struct index_state istate = INDEX_STATE_INIT(the_repository);
1227 char *old_index_env = NULL, *old_repo_index_file;
1229 remove_path(stash_index_path.buf);
1231 cp_read_tree.git_cmd = 1;
1232 strvec_pushl(&cp_read_tree.args, "read-tree", "HEAD", NULL);
1233 strvec_pushf(&cp_read_tree.env, "GIT_INDEX_FILE=%s",
1234 stash_index_path.buf);
1235 if (run_command(&cp_read_tree)) {
1236 ret = -1;
1237 goto done;
1240 /* Find out what the user wants. */
1241 old_repo_index_file = the_repository->index_file;
1242 the_repository->index_file = stash_index_path.buf;
1243 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
1244 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
1246 ret = !!run_add_p(the_repository, ADD_P_STASH, NULL, ps);
1248 the_repository->index_file = old_repo_index_file;
1249 if (old_index_env && *old_index_env)
1250 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
1251 else
1252 unsetenv(INDEX_ENVIRONMENT);
1253 FREE_AND_NULL(old_index_env);
1255 /* State of the working tree. */
1256 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1257 NULL)) {
1258 ret = -1;
1259 goto done;
1262 cp_diff_tree.git_cmd = 1;
1263 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1264 oid_to_hex(&info->w_tree), "--", NULL);
1265 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1266 ret = -1;
1267 goto done;
1270 if (!out_patch->len) {
1271 if (!quiet)
1272 fprintf_ln(stderr, _("No changes selected"));
1273 ret = 1;
1276 done:
1277 release_index(&istate);
1278 remove_path(stash_index_path.buf);
1279 return ret;
1282 static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
1284 int ret = 0;
1285 struct rev_info rev;
1286 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1287 struct strbuf diff_output = STRBUF_INIT;
1288 struct index_state istate = INDEX_STATE_INIT(the_repository);
1290 repo_init_revisions(the_repository, &rev, NULL);
1291 copy_pathspec(&rev.prune_data, ps);
1293 set_alternate_index_output(stash_index_path.buf);
1294 if (reset_tree(&info->i_tree, 0, 0)) {
1295 ret = -1;
1296 goto done;
1298 set_alternate_index_output(NULL);
1300 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1301 rev.diffopt.format_callback = add_diff_to_buf;
1302 rev.diffopt.format_callback_data = &diff_output;
1304 if (repo_read_index_preload(the_repository, &rev.diffopt.pathspec, 0) < 0) {
1305 ret = -1;
1306 goto done;
1309 add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1310 "");
1311 run_diff_index(&rev, 0);
1313 cp_upd_index.git_cmd = 1;
1314 strvec_pushl(&cp_upd_index.args, "update-index",
1315 "--ignore-skip-worktree-entries",
1316 "-z", "--add", "--remove", "--stdin", NULL);
1317 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1318 stash_index_path.buf);
1320 if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1321 NULL, 0, NULL, 0)) {
1322 ret = -1;
1323 goto done;
1326 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1327 NULL)) {
1328 ret = -1;
1329 goto done;
1332 done:
1333 release_index(&istate);
1334 release_revisions(&rev);
1335 strbuf_release(&diff_output);
1336 remove_path(stash_index_path.buf);
1337 return ret;
1340 static int do_create_stash(const struct pathspec *ps, struct strbuf *stash_msg_buf,
1341 int include_untracked, int patch_mode, int only_staged,
1342 struct stash_info *info, struct strbuf *patch,
1343 int quiet)
1345 int ret = 0;
1346 int flags = 0;
1347 int untracked_commit_option = 0;
1348 const char *head_short_sha1 = NULL;
1349 const char *branch_ref = NULL;
1350 const char *branch_name = "(no branch)";
1351 struct commit *head_commit = NULL;
1352 struct commit_list *parents = NULL;
1353 struct strbuf msg = STRBUF_INIT;
1354 struct strbuf commit_tree_label = STRBUF_INIT;
1355 struct strbuf untracked_files = STRBUF_INIT;
1357 prepare_fallback_ident("git stash", "git@stash");
1359 repo_read_index_preload(the_repository, NULL, 0);
1360 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1361 NULL, NULL, NULL) < 0) {
1362 ret = -1;
1363 goto done;
1366 if (repo_get_oid(the_repository, "HEAD", &info->b_commit)) {
1367 if (!quiet)
1368 fprintf_ln(stderr, _("You do not have "
1369 "the initial commit yet"));
1370 ret = -1;
1371 goto done;
1372 } else {
1373 head_commit = lookup_commit(the_repository, &info->b_commit);
1376 if (!check_changes(ps, include_untracked, &untracked_files)) {
1377 ret = 1;
1378 goto done;
1381 branch_ref = resolve_ref_unsafe("HEAD", 0, NULL, &flags);
1382 if (flags & REF_ISSYMREF)
1383 skip_prefix(branch_ref, "refs/heads/", &branch_name);
1384 head_short_sha1 = repo_find_unique_abbrev(the_repository,
1385 &head_commit->object.oid,
1386 DEFAULT_ABBREV);
1387 strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1388 pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1390 strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1391 commit_list_insert(head_commit, &parents);
1392 if (write_index_as_tree(&info->i_tree, &the_index, get_index_file(), 0,
1393 NULL) ||
1394 commit_tree(commit_tree_label.buf, commit_tree_label.len,
1395 &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1396 if (!quiet)
1397 fprintf_ln(stderr, _("Cannot save the current "
1398 "index state"));
1399 ret = -1;
1400 goto done;
1403 if (include_untracked) {
1404 if (save_untracked_files(info, &msg, untracked_files)) {
1405 if (!quiet)
1406 fprintf_ln(stderr, _("Cannot save "
1407 "the untracked files"));
1408 ret = -1;
1409 goto done;
1411 untracked_commit_option = 1;
1413 if (patch_mode) {
1414 ret = stash_patch(info, ps, patch, quiet);
1415 if (ret < 0) {
1416 if (!quiet)
1417 fprintf_ln(stderr, _("Cannot save the current "
1418 "worktree state"));
1419 goto done;
1420 } else if (ret > 0) {
1421 goto done;
1423 } else if (only_staged) {
1424 ret = stash_staged(info, patch, quiet);
1425 if (ret < 0) {
1426 if (!quiet)
1427 fprintf_ln(stderr, _("Cannot save the current "
1428 "staged state"));
1429 goto done;
1430 } else if (ret > 0) {
1431 goto done;
1433 } else {
1434 if (stash_working_tree(info, ps)) {
1435 if (!quiet)
1436 fprintf_ln(stderr, _("Cannot save the current "
1437 "worktree state"));
1438 ret = -1;
1439 goto done;
1443 if (!stash_msg_buf->len)
1444 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1445 else
1446 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1449 * `parents` will be empty after calling `commit_tree()`, so there is
1450 * no need to call `free_commit_list()`
1452 parents = NULL;
1453 if (untracked_commit_option)
1454 commit_list_insert(lookup_commit(the_repository,
1455 &info->u_commit),
1456 &parents);
1457 commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1458 &parents);
1459 commit_list_insert(head_commit, &parents);
1461 if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1462 parents, &info->w_commit, NULL, NULL)) {
1463 if (!quiet)
1464 fprintf_ln(stderr, _("Cannot record "
1465 "working tree state"));
1466 ret = -1;
1467 goto done;
1470 done:
1471 strbuf_release(&commit_tree_label);
1472 strbuf_release(&msg);
1473 strbuf_release(&untracked_files);
1474 return ret;
1477 static int create_stash(int argc, const char **argv, const char *prefix UNUSED)
1479 int ret;
1480 struct strbuf stash_msg_buf = STRBUF_INIT;
1481 struct stash_info info = STASH_INFO_INIT;
1482 struct pathspec ps;
1484 /* Starting with argv[1], since argv[0] is "create" */
1485 strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
1487 memset(&ps, 0, sizeof(ps));
1488 if (!check_changes_tracked_files(&ps))
1489 return 0;
1491 ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, 0, &info,
1492 NULL, 0);
1493 if (!ret)
1494 printf_ln("%s", oid_to_hex(&info.w_commit));
1496 free_stash_info(&info);
1497 strbuf_release(&stash_msg_buf);
1498 return ret;
1501 static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int quiet,
1502 int keep_index, int patch_mode, int include_untracked, int only_staged)
1504 int ret = 0;
1505 struct stash_info info = STASH_INFO_INIT;
1506 struct strbuf patch = STRBUF_INIT;
1507 struct strbuf stash_msg_buf = STRBUF_INIT;
1508 struct strbuf untracked_files = STRBUF_INIT;
1510 if (patch_mode && keep_index == -1)
1511 keep_index = 1;
1513 if (patch_mode && include_untracked) {
1514 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1515 " or --all at the same time"));
1516 ret = -1;
1517 goto done;
1520 /* --patch overrides --staged */
1521 if (patch_mode)
1522 only_staged = 0;
1524 if (only_staged && include_untracked) {
1525 fprintf_ln(stderr, _("Can't use --staged and --include-untracked"
1526 " or --all at the same time"));
1527 ret = -1;
1528 goto done;
1531 repo_read_index_preload(the_repository, NULL, 0);
1532 if (!include_untracked && ps->nr) {
1533 int i;
1534 char *ps_matched = xcalloc(ps->nr, 1);
1536 /* TODO: audit for interaction with sparse-index. */
1537 ensure_full_index(&the_index);
1538 for (i = 0; i < the_index.cache_nr; i++)
1539 ce_path_match(&the_index, the_index.cache[i], ps,
1540 ps_matched);
1542 if (report_path_error(ps_matched, ps)) {
1543 fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1544 ret = -1;
1545 free(ps_matched);
1546 goto done;
1548 free(ps_matched);
1551 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1552 NULL, NULL, NULL)) {
1553 ret = -1;
1554 goto done;
1557 if (!check_changes(ps, include_untracked, &untracked_files)) {
1558 if (!quiet)
1559 printf_ln(_("No local changes to save"));
1560 goto done;
1563 if (!reflog_exists(ref_stash) && do_clear_stash()) {
1564 ret = -1;
1565 if (!quiet)
1566 fprintf_ln(stderr, _("Cannot initialize stash"));
1567 goto done;
1570 if (stash_msg)
1571 strbuf_addstr(&stash_msg_buf, stash_msg);
1572 if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode, only_staged,
1573 &info, &patch, quiet)) {
1574 ret = -1;
1575 goto done;
1578 if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1579 ret = -1;
1580 if (!quiet)
1581 fprintf_ln(stderr, _("Cannot save the current status"));
1582 goto done;
1585 if (!quiet)
1586 printf_ln(_("Saved working directory and index state %s"),
1587 stash_msg_buf.buf);
1589 if (!(patch_mode || only_staged)) {
1590 if (include_untracked && !ps->nr) {
1591 struct child_process cp = CHILD_PROCESS_INIT;
1593 cp.git_cmd = 1;
1594 if (startup_info->original_cwd) {
1595 cp.dir = startup_info->original_cwd;
1596 strvec_pushf(&cp.env, "%s=%s",
1597 GIT_WORK_TREE_ENVIRONMENT,
1598 the_repository->worktree);
1600 strvec_pushl(&cp.args, "clean", "--force",
1601 "--quiet", "-d", ":/", NULL);
1602 if (include_untracked == INCLUDE_ALL_FILES)
1603 strvec_push(&cp.args, "-x");
1604 if (run_command(&cp)) {
1605 ret = -1;
1606 goto done;
1609 discard_index(&the_index);
1610 if (ps->nr) {
1611 struct child_process cp_add = CHILD_PROCESS_INIT;
1612 struct child_process cp_diff = CHILD_PROCESS_INIT;
1613 struct child_process cp_apply = CHILD_PROCESS_INIT;
1614 struct strbuf out = STRBUF_INIT;
1616 cp_add.git_cmd = 1;
1617 strvec_push(&cp_add.args, "add");
1618 if (!include_untracked)
1619 strvec_push(&cp_add.args, "-u");
1620 if (include_untracked == INCLUDE_ALL_FILES)
1621 strvec_push(&cp_add.args, "--force");
1622 strvec_push(&cp_add.args, "--");
1623 add_pathspecs(&cp_add.args, ps);
1624 if (run_command(&cp_add)) {
1625 ret = -1;
1626 goto done;
1629 cp_diff.git_cmd = 1;
1630 strvec_pushl(&cp_diff.args, "diff-index", "-p",
1631 "--cached", "--binary", "HEAD", "--",
1632 NULL);
1633 add_pathspecs(&cp_diff.args, ps);
1634 if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1635 ret = -1;
1636 goto done;
1639 cp_apply.git_cmd = 1;
1640 strvec_pushl(&cp_apply.args, "apply", "--index",
1641 "-R", NULL);
1642 if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1643 NULL, 0)) {
1644 ret = -1;
1645 goto done;
1647 } else {
1648 struct child_process cp = CHILD_PROCESS_INIT;
1649 cp.git_cmd = 1;
1650 /* BUG: this nukes untracked files in the way */
1651 strvec_pushl(&cp.args, "reset", "--hard", "-q",
1652 "--no-recurse-submodules", NULL);
1653 if (run_command(&cp)) {
1654 ret = -1;
1655 goto done;
1659 if (keep_index == 1 && !is_null_oid(&info.i_tree)) {
1660 struct child_process cp = CHILD_PROCESS_INIT;
1662 cp.git_cmd = 1;
1663 strvec_pushl(&cp.args, "checkout", "--no-overlay",
1664 oid_to_hex(&info.i_tree), "--", NULL);
1665 if (!ps->nr)
1666 strvec_push(&cp.args, ":/");
1667 else
1668 add_pathspecs(&cp.args, ps);
1669 if (run_command(&cp)) {
1670 ret = -1;
1671 goto done;
1674 goto done;
1675 } else {
1676 struct child_process cp = CHILD_PROCESS_INIT;
1678 cp.git_cmd = 1;
1679 strvec_pushl(&cp.args, "apply", "-R", NULL);
1681 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1682 if (!quiet)
1683 fprintf_ln(stderr, _("Cannot remove "
1684 "worktree changes"));
1685 ret = -1;
1686 goto done;
1689 if (keep_index < 1) {
1690 struct child_process cp = CHILD_PROCESS_INIT;
1692 cp.git_cmd = 1;
1693 strvec_pushl(&cp.args, "reset", "-q", "--refresh", "--",
1694 NULL);
1695 add_pathspecs(&cp.args, ps);
1696 if (run_command(&cp)) {
1697 ret = -1;
1698 goto done;
1701 goto done;
1704 done:
1705 strbuf_release(&patch);
1706 free_stash_info(&info);
1707 strbuf_release(&stash_msg_buf);
1708 strbuf_release(&untracked_files);
1709 return ret;
1712 static int push_stash(int argc, const char **argv, const char *prefix,
1713 int push_assumed)
1715 int force_assume = 0;
1716 int keep_index = -1;
1717 int only_staged = 0;
1718 int patch_mode = 0;
1719 int include_untracked = 0;
1720 int quiet = 0;
1721 int pathspec_file_nul = 0;
1722 const char *stash_msg = NULL;
1723 const char *pathspec_from_file = NULL;
1724 struct pathspec ps;
1725 struct option options[] = {
1726 OPT_BOOL('k', "keep-index", &keep_index,
1727 N_("keep index")),
1728 OPT_BOOL('S', "staged", &only_staged,
1729 N_("stash staged changes only")),
1730 OPT_BOOL('p', "patch", &patch_mode,
1731 N_("stash in patch mode")),
1732 OPT__QUIET(&quiet, N_("quiet mode")),
1733 OPT_BOOL('u', "include-untracked", &include_untracked,
1734 N_("include untracked files in stash")),
1735 OPT_SET_INT('a', "all", &include_untracked,
1736 N_("include ignore files"), 2),
1737 OPT_STRING('m', "message", &stash_msg, N_("message"),
1738 N_("stash message")),
1739 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1740 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1741 OPT_END()
1743 int ret;
1745 if (argc) {
1746 force_assume = !strcmp(argv[0], "-p");
1747 argc = parse_options(argc, argv, prefix, options,
1748 push_assumed ? git_stash_usage :
1749 git_stash_push_usage,
1750 PARSE_OPT_KEEP_DASHDASH);
1753 if (argc) {
1754 if (!strcmp(argv[0], "--")) {
1755 argc--;
1756 argv++;
1757 } else if (push_assumed && !force_assume) {
1758 die("subcommand wasn't specified; 'push' can't be assumed due to unexpected token '%s'",
1759 argv[0]);
1763 parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1764 prefix, argv);
1766 if (pathspec_from_file) {
1767 if (patch_mode)
1768 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1770 if (only_staged)
1771 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--staged");
1773 if (ps.nr)
1774 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1776 parse_pathspec_file(&ps, 0,
1777 PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1778 prefix, pathspec_from_file, pathspec_file_nul);
1779 } else if (pathspec_file_nul) {
1780 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1783 ret = do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
1784 include_untracked, only_staged);
1785 clear_pathspec(&ps);
1786 return ret;
1789 static int push_stash_unassumed(int argc, const char **argv, const char *prefix)
1791 return push_stash(argc, argv, prefix, 0);
1794 static int save_stash(int argc, const char **argv, const char *prefix)
1796 int keep_index = -1;
1797 int only_staged = 0;
1798 int patch_mode = 0;
1799 int include_untracked = 0;
1800 int quiet = 0;
1801 int ret = 0;
1802 const char *stash_msg = NULL;
1803 struct pathspec ps;
1804 struct strbuf stash_msg_buf = STRBUF_INIT;
1805 struct option options[] = {
1806 OPT_BOOL('k', "keep-index", &keep_index,
1807 N_("keep index")),
1808 OPT_BOOL('S', "staged", &only_staged,
1809 N_("stash staged changes only")),
1810 OPT_BOOL('p', "patch", &patch_mode,
1811 N_("stash in patch mode")),
1812 OPT__QUIET(&quiet, N_("quiet mode")),
1813 OPT_BOOL('u', "include-untracked", &include_untracked,
1814 N_("include untracked files in stash")),
1815 OPT_SET_INT('a', "all", &include_untracked,
1816 N_("include ignore files"), 2),
1817 OPT_STRING('m', "message", &stash_msg, "message",
1818 N_("stash message")),
1819 OPT_END()
1822 argc = parse_options(argc, argv, prefix, options,
1823 git_stash_save_usage,
1824 PARSE_OPT_KEEP_DASHDASH);
1826 if (argc)
1827 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
1829 memset(&ps, 0, sizeof(ps));
1830 ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
1831 patch_mode, include_untracked, only_staged);
1833 strbuf_release(&stash_msg_buf);
1834 return ret;
1837 int cmd_stash(int argc, const char **argv, const char *prefix)
1839 pid_t pid = getpid();
1840 const char *index_file;
1841 struct strvec args = STRVEC_INIT;
1842 parse_opt_subcommand_fn *fn = NULL;
1843 struct option options[] = {
1844 OPT_SUBCOMMAND("apply", &fn, apply_stash),
1845 OPT_SUBCOMMAND("clear", &fn, clear_stash),
1846 OPT_SUBCOMMAND("drop", &fn, drop_stash),
1847 OPT_SUBCOMMAND("pop", &fn, pop_stash),
1848 OPT_SUBCOMMAND("branch", &fn, branch_stash),
1849 OPT_SUBCOMMAND("list", &fn, list_stash),
1850 OPT_SUBCOMMAND("show", &fn, show_stash),
1851 OPT_SUBCOMMAND("store", &fn, store_stash),
1852 OPT_SUBCOMMAND("create", &fn, create_stash),
1853 OPT_SUBCOMMAND("push", &fn, push_stash_unassumed),
1854 OPT_SUBCOMMAND_F("save", &fn, save_stash, PARSE_OPT_NOCOMPLETE),
1855 OPT_END()
1858 git_config(git_stash_config, NULL);
1860 argc = parse_options(argc, argv, prefix, options, git_stash_usage,
1861 PARSE_OPT_SUBCOMMAND_OPTIONAL |
1862 PARSE_OPT_KEEP_UNKNOWN_OPT |
1863 PARSE_OPT_KEEP_DASHDASH);
1865 prepare_repo_settings(the_repository);
1866 the_repository->settings.command_requires_full_index = 0;
1868 index_file = get_index_file();
1869 strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
1870 (uintmax_t)pid);
1872 if (fn)
1873 return !!fn(argc, argv, prefix);
1874 else if (!argc)
1875 return !!push_stash_unassumed(0, NULL, prefix);
1877 /* Assume 'stash push' */
1878 strvec_push(&args, "push");
1879 strvec_pushv(&args, argv);
1880 return !!push_stash(args.nr, args.v, prefix, 1);