notes.c: use designated initializers for clarity
[git/debian.git] / builtin / stash.c
blob735d27039e1865369018f127666a009928e8fda4
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 "hex.h"
8 #include "parse-options.h"
9 #include "refs.h"
10 #include "lockfile.h"
11 #include "cache-tree.h"
12 #include "unpack-trees.h"
13 #include "merge-recursive.h"
14 #include "merge-ort-wrappers.h"
15 #include "strvec.h"
16 #include "run-command.h"
17 #include "dir.h"
18 #include "entry.h"
19 #include "rerere.h"
20 #include "revision.h"
21 #include "setup.h"
22 #include "log-tree.h"
23 #include "diffcore.h"
24 #include "exec-cmd.h"
25 #include "reflog.h"
26 #include "add-interactive.h"
28 #define INCLUDE_ALL_FILES 2
30 #define BUILTIN_STASH_LIST_USAGE \
31 N_("git stash list [<log-options>]")
32 #define BUILTIN_STASH_SHOW_USAGE \
33 N_("git stash show [-u | --include-untracked | --only-untracked] [<diff-options>] [<stash>]")
34 #define BUILTIN_STASH_DROP_USAGE \
35 N_("git stash drop [-q | --quiet] [<stash>]")
36 #define BUILTIN_STASH_POP_USAGE \
37 N_("git stash pop [--index] [-q | --quiet] [<stash>]")
38 #define BUILTIN_STASH_APPLY_USAGE \
39 N_("git stash apply [--index] [-q | --quiet] [<stash>]")
40 #define BUILTIN_STASH_BRANCH_USAGE \
41 N_("git stash branch <branchname> [<stash>]")
42 #define BUILTIN_STASH_STORE_USAGE \
43 N_("git stash store [(-m | --message) <message>] [-q | --quiet] <commit>")
44 #define BUILTIN_STASH_PUSH_USAGE \
45 N_("git stash [push [-p | --patch] [-S | --staged] [-k | --[no-]keep-index] [-q | --quiet]\n" \
46 " [-u | --include-untracked] [-a | --all] [(-m | --message) <message>]\n" \
47 " [--pathspec-from-file=<file> [--pathspec-file-nul]]\n" \
48 " [--] [<pathspec>...]]")
49 #define BUILTIN_STASH_SAVE_USAGE \
50 N_("git stash save [-p | --patch] [-S | --staged] [-k | --[no-]keep-index] [-q | --quiet]\n" \
51 " [-u | --include-untracked] [-a | --all] [<message>]")
52 #define BUILTIN_STASH_CREATE_USAGE \
53 N_("git stash create [<message>]")
54 #define BUILTIN_STASH_CLEAR_USAGE \
55 "git stash clear"
57 static const char * const git_stash_usage[] = {
58 BUILTIN_STASH_LIST_USAGE,
59 BUILTIN_STASH_SHOW_USAGE,
60 BUILTIN_STASH_DROP_USAGE,
61 BUILTIN_STASH_POP_USAGE,
62 BUILTIN_STASH_APPLY_USAGE,
63 BUILTIN_STASH_BRANCH_USAGE,
64 BUILTIN_STASH_PUSH_USAGE,
65 BUILTIN_STASH_SAVE_USAGE,
66 BUILTIN_STASH_CLEAR_USAGE,
67 BUILTIN_STASH_CREATE_USAGE,
68 BUILTIN_STASH_STORE_USAGE,
69 NULL
72 static const char * const git_stash_list_usage[] = {
73 BUILTIN_STASH_LIST_USAGE,
74 NULL
77 static const char * const git_stash_show_usage[] = {
78 BUILTIN_STASH_SHOW_USAGE,
79 NULL
82 static const char * const git_stash_drop_usage[] = {
83 BUILTIN_STASH_DROP_USAGE,
84 NULL
87 static const char * const git_stash_pop_usage[] = {
88 BUILTIN_STASH_POP_USAGE,
89 NULL
92 static const char * const git_stash_apply_usage[] = {
93 BUILTIN_STASH_APPLY_USAGE,
94 NULL
97 static const char * const git_stash_branch_usage[] = {
98 BUILTIN_STASH_BRANCH_USAGE,
99 NULL
102 static const char * const git_stash_clear_usage[] = {
103 BUILTIN_STASH_CLEAR_USAGE,
104 NULL
107 static const char * const git_stash_store_usage[] = {
108 BUILTIN_STASH_STORE_USAGE,
109 NULL
112 static const char * const git_stash_push_usage[] = {
113 BUILTIN_STASH_PUSH_USAGE,
114 NULL
117 static const char * const git_stash_save_usage[] = {
118 BUILTIN_STASH_SAVE_USAGE,
119 NULL
122 static const char ref_stash[] = "refs/stash";
123 static struct strbuf stash_index_path = STRBUF_INIT;
126 * w_commit is set to the commit containing the working tree
127 * b_commit is set to the base commit
128 * i_commit is set to the commit containing the index tree
129 * u_commit is set to the commit containing the untracked files tree
130 * w_tree is set to the working tree
131 * b_tree is set to the base tree
132 * i_tree is set to the index tree
133 * u_tree is set to the untracked files tree
135 struct stash_info {
136 struct object_id w_commit;
137 struct object_id b_commit;
138 struct object_id i_commit;
139 struct object_id u_commit;
140 struct object_id w_tree;
141 struct object_id b_tree;
142 struct object_id i_tree;
143 struct object_id u_tree;
144 struct strbuf revision;
145 int is_stash_ref;
146 int has_u;
149 #define STASH_INFO_INIT { \
150 .revision = STRBUF_INIT, \
153 static void free_stash_info(struct stash_info *info)
155 strbuf_release(&info->revision);
158 static void assert_stash_like(struct stash_info *info, const char *revision)
160 if (get_oidf(&info->b_commit, "%s^1", revision) ||
161 get_oidf(&info->w_tree, "%s:", revision) ||
162 get_oidf(&info->b_tree, "%s^1:", revision) ||
163 get_oidf(&info->i_tree, "%s^2:", revision))
164 die(_("'%s' is not a stash-like commit"), revision);
167 static int get_stash_info(struct stash_info *info, int argc, const char **argv)
169 int ret;
170 char *end_of_rev;
171 char *expanded_ref;
172 const char *revision;
173 const char *commit = NULL;
174 struct object_id dummy;
175 struct strbuf symbolic = STRBUF_INIT;
177 if (argc > 1) {
178 int i;
179 struct strbuf refs_msg = STRBUF_INIT;
181 for (i = 0; i < argc; i++)
182 strbuf_addf(&refs_msg, " '%s'", argv[i]);
184 fprintf_ln(stderr, _("Too many revisions specified:%s"),
185 refs_msg.buf);
186 strbuf_release(&refs_msg);
188 return -1;
191 if (argc == 1)
192 commit = argv[0];
194 if (!commit) {
195 if (!ref_exists(ref_stash)) {
196 fprintf_ln(stderr, _("No stash entries found."));
197 return -1;
200 strbuf_addf(&info->revision, "%s@{0}", ref_stash);
201 } else if (strspn(commit, "0123456789") == strlen(commit)) {
202 strbuf_addf(&info->revision, "%s@{%s}", ref_stash, commit);
203 } else {
204 strbuf_addstr(&info->revision, commit);
207 revision = info->revision.buf;
209 if (repo_get_oid(the_repository, revision, &info->w_commit))
210 return error(_("%s is not a valid reference"), revision);
212 assert_stash_like(info, revision);
214 info->has_u = !get_oidf(&info->u_tree, "%s^3:", revision);
216 end_of_rev = strchrnul(revision, '@');
217 strbuf_add(&symbolic, revision, end_of_rev - revision);
219 ret = repo_dwim_ref(the_repository, symbolic.buf, symbolic.len,
220 &dummy, &expanded_ref, 0);
221 strbuf_release(&symbolic);
222 switch (ret) {
223 case 0: /* Not found, but valid ref */
224 info->is_stash_ref = 0;
225 break;
226 case 1:
227 info->is_stash_ref = !strcmp(expanded_ref, ref_stash);
228 break;
229 default: /* Invalid or ambiguous */
230 break;
233 free(expanded_ref);
234 return !(ret == 0 || ret == 1);
237 static int do_clear_stash(void)
239 struct object_id obj;
240 if (repo_get_oid(the_repository, ref_stash, &obj))
241 return 0;
243 return delete_ref(NULL, ref_stash, &obj, 0);
246 static int clear_stash(int argc, const char **argv, const char *prefix)
248 struct option options[] = {
249 OPT_END()
252 argc = parse_options(argc, argv, prefix, options,
253 git_stash_clear_usage,
254 PARSE_OPT_STOP_AT_NON_OPTION);
256 if (argc)
257 return error(_("git stash clear with arguments is "
258 "unimplemented"));
260 return do_clear_stash();
263 static int reset_tree(struct object_id *i_tree, int update, int reset)
265 int nr_trees = 1;
266 struct unpack_trees_options opts;
267 struct tree_desc t[MAX_UNPACK_TREES];
268 struct tree *tree;
269 struct lock_file lock_file = LOCK_INIT;
271 repo_read_index_preload(the_repository, NULL, 0);
272 if (refresh_index(&the_index, REFRESH_QUIET, NULL, NULL, NULL))
273 return -1;
275 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
277 memset(&opts, 0, sizeof(opts));
279 tree = parse_tree_indirect(i_tree);
280 if (parse_tree(tree))
281 return -1;
283 init_tree_desc(t, tree->buffer, tree->size);
285 opts.head_idx = 1;
286 opts.src_index = &the_index;
287 opts.dst_index = &the_index;
288 opts.merge = 1;
289 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
290 opts.update = update;
291 if (update)
292 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
293 opts.fn = oneway_merge;
295 if (unpack_trees(nr_trees, t, &opts))
296 return -1;
298 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
299 return error(_("unable to write new index file"));
301 return 0;
304 static int diff_tree_binary(struct strbuf *out, struct object_id *w_commit)
306 struct child_process cp = CHILD_PROCESS_INIT;
307 const char *w_commit_hex = oid_to_hex(w_commit);
310 * Diff-tree would not be very hard to replace with a native function,
311 * however it should be done together with apply_cached.
313 cp.git_cmd = 1;
314 strvec_pushl(&cp.args, "diff-tree", "--binary", NULL);
315 strvec_pushf(&cp.args, "%s^2^..%s^2", w_commit_hex, w_commit_hex);
317 return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
320 static int apply_cached(struct strbuf *out)
322 struct child_process cp = CHILD_PROCESS_INIT;
325 * Apply currently only reads either from stdin or a file, thus
326 * apply_all_patches would have to be updated to optionally take a
327 * buffer.
329 cp.git_cmd = 1;
330 strvec_pushl(&cp.args, "apply", "--cached", NULL);
331 return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
334 static int reset_head(void)
336 struct child_process cp = CHILD_PROCESS_INIT;
339 * Reset is overall quite simple, however there is no current public
340 * API for resetting.
342 cp.git_cmd = 1;
343 strvec_pushl(&cp.args, "reset", "--quiet", "--refresh", NULL);
345 return run_command(&cp);
348 static int is_path_a_directory(const char *path)
351 * This function differs from abspath.c:is_directory() in that
352 * here we use lstat() instead of stat(); we do not want to
353 * follow symbolic links here.
355 struct stat st;
356 return (!lstat(path, &st) && S_ISDIR(st.st_mode));
359 static void add_diff_to_buf(struct diff_queue_struct *q,
360 struct diff_options *options,
361 void *data)
363 int i;
365 for (i = 0; i < q->nr; i++) {
366 if (is_path_a_directory(q->queue[i]->one->path))
367 continue;
369 strbuf_addstr(data, q->queue[i]->one->path);
371 /* NUL-terminate: will be fed to update-index -z */
372 strbuf_addch(data, '\0');
376 static int restore_untracked(struct object_id *u_tree)
378 int res;
379 struct child_process cp = CHILD_PROCESS_INIT;
382 * We need to run restore files from a given index, but without
383 * affecting the current index, so we use GIT_INDEX_FILE with
384 * run_command to fork processes that will not interfere.
386 cp.git_cmd = 1;
387 strvec_push(&cp.args, "read-tree");
388 strvec_push(&cp.args, oid_to_hex(u_tree));
389 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
390 stash_index_path.buf);
391 if (run_command(&cp)) {
392 remove_path(stash_index_path.buf);
393 return -1;
396 child_process_init(&cp);
397 cp.git_cmd = 1;
398 strvec_pushl(&cp.args, "checkout-index", "--all", NULL);
399 strvec_pushf(&cp.env, "GIT_INDEX_FILE=%s",
400 stash_index_path.buf);
402 res = run_command(&cp);
403 remove_path(stash_index_path.buf);
404 return res;
407 static void unstage_changes_unless_new(struct object_id *orig_tree)
410 * When we enter this function, there has been a clean merge of
411 * relevant trees, and the merge logic always stages whatever merges
412 * cleanly. We want to unstage those changes, unless it corresponds
413 * to a file that didn't exist as of orig_tree.
415 * However, if any SKIP_WORKTREE path is modified relative to
416 * orig_tree, then we want to clear the SKIP_WORKTREE bit and write
417 * it to the worktree before unstaging.
420 struct checkout state = CHECKOUT_INIT;
421 struct diff_options diff_opts;
422 struct lock_file lock = LOCK_INIT;
423 int i;
425 /* If any entries have skip_worktree set, we'll have to check 'em out */
426 state.force = 1;
427 state.quiet = 1;
428 state.refresh_cache = 1;
429 state.istate = &the_index;
432 * Step 1: get a difference between orig_tree (which corresponding
433 * to the index before a merge was run) and the current index
434 * (reflecting the changes brought in by the merge).
436 repo_diff_setup(the_repository, &diff_opts);
437 diff_opts.flags.recursive = 1;
438 diff_opts.detect_rename = 0;
439 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
440 diff_setup_done(&diff_opts);
442 do_diff_cache(orig_tree, &diff_opts);
443 diffcore_std(&diff_opts);
445 /* Iterate over the paths that changed due to the merge... */
446 for (i = 0; i < diff_queued_diff.nr; i++) {
447 struct diff_filepair *p;
448 struct cache_entry *ce;
449 int pos;
451 /* Look up the path's position in the current index. */
452 p = diff_queued_diff.queue[i];
453 pos = index_name_pos(&the_index, p->two->path,
454 strlen(p->two->path));
457 * Step 2: Place changes in the working tree
459 * Stash is about restoring changes *to the working tree*.
460 * So if the merge successfully got a new version of some
461 * path, but left it out of the working tree, then clear the
462 * SKIP_WORKTREE bit and write it to the working tree.
464 if (pos >= 0 && ce_skip_worktree(the_index.cache[pos])) {
465 struct stat st;
467 ce = the_index.cache[pos];
468 if (!lstat(ce->name, &st)) {
469 /* Conflicting path present; relocate it */
470 struct strbuf new_path = STRBUF_INIT;
471 int fd;
473 strbuf_addf(&new_path,
474 "%s.stash.XXXXXX", ce->name);
475 fd = xmkstemp(new_path.buf);
476 close(fd);
477 printf(_("WARNING: Untracked file in way of "
478 "tracked file! Renaming\n "
479 " %s -> %s\n"
480 " to make room.\n"),
481 ce->name, new_path.buf);
482 if (rename(ce->name, new_path.buf))
483 die("Failed to move %s to %s\n",
484 ce->name, new_path.buf);
485 strbuf_release(&new_path);
487 checkout_entry(ce, &state, NULL, NULL);
488 ce->ce_flags &= ~CE_SKIP_WORKTREE;
492 * Step 3: "unstage" changes, as long as they are still tracked
494 if (p->one->oid_valid) {
496 * Path existed in orig_tree; restore index entry
497 * from that tree in order to "unstage" the changes.
499 int option = ADD_CACHE_OK_TO_REPLACE;
500 if (pos < 0)
501 option = ADD_CACHE_OK_TO_ADD;
503 ce = make_cache_entry(&the_index,
504 p->one->mode,
505 &p->one->oid,
506 p->one->path,
507 0, 0);
508 add_index_entry(&the_index, ce, option);
511 diff_flush(&diff_opts);
514 * Step 4: write the new index to disk
516 repo_hold_locked_index(the_repository, &lock, LOCK_DIE_ON_ERROR);
517 if (write_locked_index(&the_index, &lock,
518 COMMIT_LOCK | SKIP_IF_UNCHANGED))
519 die(_("Unable to write index."));
522 static int do_apply_stash(const char *prefix, struct stash_info *info,
523 int index, int quiet)
525 int clean, ret;
526 int has_index = index;
527 struct merge_options o;
528 struct object_id c_tree;
529 struct object_id index_tree;
530 struct tree *head, *merge, *merge_base;
531 struct lock_file lock = LOCK_INIT;
533 repo_read_index_preload(the_repository, NULL, 0);
534 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
535 NULL, NULL, NULL))
536 return -1;
538 if (write_index_as_tree(&c_tree, &the_index, get_index_file(), 0,
539 NULL))
540 return error(_("cannot apply a stash in the middle of a merge"));
542 if (index) {
543 if (oideq(&info->b_tree, &info->i_tree) ||
544 oideq(&c_tree, &info->i_tree)) {
545 has_index = 0;
546 } else {
547 struct strbuf out = STRBUF_INIT;
549 if (diff_tree_binary(&out, &info->w_commit)) {
550 strbuf_release(&out);
551 return error(_("could not generate diff %s^!."),
552 oid_to_hex(&info->w_commit));
555 ret = apply_cached(&out);
556 strbuf_release(&out);
557 if (ret)
558 return error(_("conflicts in index. "
559 "Try without --index."));
561 discard_index(&the_index);
562 repo_read_index(the_repository);
563 if (write_index_as_tree(&index_tree, &the_index,
564 get_index_file(), 0, NULL))
565 return error(_("could not save index tree"));
567 reset_head();
568 discard_index(&the_index);
569 repo_read_index(the_repository);
573 init_merge_options(&o, the_repository);
575 o.branch1 = "Updated upstream";
576 o.branch2 = "Stashed changes";
577 o.ancestor = "Stash base";
579 if (oideq(&info->b_tree, &c_tree))
580 o.branch1 = "Version stash was based on";
582 if (quiet)
583 o.verbosity = 0;
585 if (o.verbosity >= 3)
586 printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
588 head = lookup_tree(o.repo, &c_tree);
589 merge = lookup_tree(o.repo, &info->w_tree);
590 merge_base = lookup_tree(o.repo, &info->b_tree);
592 repo_hold_locked_index(o.repo, &lock, LOCK_DIE_ON_ERROR);
593 clean = merge_ort_nonrecursive(&o, head, merge, merge_base);
596 * If 'clean' >= 0, reverse the value for 'ret' so 'ret' is 0 when the
597 * merge was clean, and nonzero if the merge was unclean or encountered
598 * an error.
600 ret = clean >= 0 ? !clean : clean;
602 if (ret < 0)
603 rollback_lock_file(&lock);
604 else if (write_locked_index(o.repo->index, &lock,
605 COMMIT_LOCK | SKIP_IF_UNCHANGED))
606 ret = error(_("could not write index"));
608 if (ret) {
609 repo_rerere(the_repository, 0);
611 if (index)
612 fprintf_ln(stderr, _("Index was not unstashed."));
614 goto restore_untracked;
617 if (has_index) {
618 if (reset_tree(&index_tree, 0, 0))
619 ret = -1;
620 } else {
621 unstage_changes_unless_new(&c_tree);
624 restore_untracked:
625 if (info->has_u && restore_untracked(&info->u_tree))
626 ret = error(_("could not restore untracked files from stash"));
628 if (!quiet) {
629 struct child_process cp = CHILD_PROCESS_INIT;
632 * Status is quite simple and could be replaced with calls to
633 * wt_status in the future, but it adds complexities which may
634 * require more tests.
636 cp.git_cmd = 1;
637 cp.dir = prefix;
638 strvec_pushf(&cp.env, GIT_WORK_TREE_ENVIRONMENT"=%s",
639 absolute_path(get_git_work_tree()));
640 strvec_pushf(&cp.env, GIT_DIR_ENVIRONMENT"=%s",
641 absolute_path(get_git_dir()));
642 strvec_push(&cp.args, "status");
643 run_command(&cp);
646 return ret;
649 static int apply_stash(int argc, const char **argv, const char *prefix)
651 int ret = -1;
652 int quiet = 0;
653 int index = 0;
654 struct stash_info info = STASH_INFO_INIT;
655 struct option options[] = {
656 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
657 OPT_BOOL(0, "index", &index,
658 N_("attempt to recreate the index")),
659 OPT_END()
662 argc = parse_options(argc, argv, prefix, options,
663 git_stash_apply_usage, 0);
665 if (get_stash_info(&info, argc, argv))
666 goto cleanup;
668 ret = do_apply_stash(prefix, &info, index, quiet);
669 cleanup:
670 free_stash_info(&info);
671 return ret;
674 static int reject_reflog_ent(struct object_id *ooid UNUSED,
675 struct object_id *noid UNUSED,
676 const char *email UNUSED,
677 timestamp_t timestamp UNUSED,
678 int tz UNUSED, const char *message UNUSED,
679 void *cb_data UNUSED)
681 return 1;
684 static int reflog_is_empty(const char *refname)
686 return !for_each_reflog_ent(refname, reject_reflog_ent, NULL);
689 static int do_drop_stash(struct stash_info *info, int quiet)
691 if (!reflog_delete(info->revision.buf,
692 EXPIRE_REFLOGS_REWRITE | EXPIRE_REFLOGS_UPDATE_REF,
693 0)) {
694 if (!quiet)
695 printf_ln(_("Dropped %s (%s)"), info->revision.buf,
696 oid_to_hex(&info->w_commit));
697 } else {
698 return error(_("%s: Could not drop stash entry"),
699 info->revision.buf);
702 if (reflog_is_empty(ref_stash))
703 do_clear_stash();
705 return 0;
708 static int get_stash_info_assert(struct stash_info *info, int argc,
709 const char **argv)
711 int ret = get_stash_info(info, argc, argv);
713 if (ret < 0)
714 return ret;
716 if (!info->is_stash_ref)
717 return error(_("'%s' is not a stash reference"), info->revision.buf);
719 return 0;
722 static int drop_stash(int argc, const char **argv, const char *prefix)
724 int ret = -1;
725 int quiet = 0;
726 struct stash_info info = STASH_INFO_INIT;
727 struct option options[] = {
728 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
729 OPT_END()
732 argc = parse_options(argc, argv, prefix, options,
733 git_stash_drop_usage, 0);
735 if (get_stash_info_assert(&info, argc, argv))
736 goto cleanup;
738 ret = do_drop_stash(&info, quiet);
739 cleanup:
740 free_stash_info(&info);
741 return ret;
744 static int pop_stash(int argc, const char **argv, const char *prefix)
746 int ret = -1;
747 int index = 0;
748 int quiet = 0;
749 struct stash_info info = STASH_INFO_INIT;
750 struct option options[] = {
751 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
752 OPT_BOOL(0, "index", &index,
753 N_("attempt to recreate the index")),
754 OPT_END()
757 argc = parse_options(argc, argv, prefix, options,
758 git_stash_pop_usage, 0);
760 if (get_stash_info_assert(&info, argc, argv))
761 goto cleanup;
763 if ((ret = do_apply_stash(prefix, &info, index, quiet)))
764 printf_ln(_("The stash entry is kept in case "
765 "you need it again."));
766 else
767 ret = do_drop_stash(&info, quiet);
769 cleanup:
770 free_stash_info(&info);
771 return ret;
774 static int branch_stash(int argc, const char **argv, const char *prefix)
776 int ret = -1;
777 const char *branch = NULL;
778 struct stash_info info = STASH_INFO_INIT;
779 struct child_process cp = CHILD_PROCESS_INIT;
780 struct option options[] = {
781 OPT_END()
784 argc = parse_options(argc, argv, prefix, options,
785 git_stash_branch_usage, 0);
787 if (!argc) {
788 fprintf_ln(stderr, _("No branch name specified"));
789 return -1;
792 branch = argv[0];
794 if (get_stash_info(&info, argc - 1, argv + 1))
795 goto cleanup;
797 cp.git_cmd = 1;
798 strvec_pushl(&cp.args, "checkout", "-b", NULL);
799 strvec_push(&cp.args, branch);
800 strvec_push(&cp.args, oid_to_hex(&info.b_commit));
801 ret = run_command(&cp);
802 if (!ret)
803 ret = do_apply_stash(prefix, &info, 1, 0);
804 if (!ret && info.is_stash_ref)
805 ret = do_drop_stash(&info, 0);
807 cleanup:
808 free_stash_info(&info);
809 return ret;
812 static int list_stash(int argc, const char **argv, const char *prefix)
814 struct child_process cp = CHILD_PROCESS_INIT;
815 struct option options[] = {
816 OPT_END()
819 argc = parse_options(argc, argv, prefix, options,
820 git_stash_list_usage,
821 PARSE_OPT_KEEP_UNKNOWN_OPT);
823 if (!ref_exists(ref_stash))
824 return 0;
826 cp.git_cmd = 1;
827 strvec_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
828 "--first-parent", NULL);
829 strvec_pushv(&cp.args, argv);
830 strvec_push(&cp.args, ref_stash);
831 strvec_push(&cp.args, "--");
832 return run_command(&cp);
835 static int show_stat = 1;
836 static int show_patch;
837 static int show_include_untracked;
839 static int git_stash_config(const char *var, const char *value, void *cb)
841 if (!strcmp(var, "stash.showstat")) {
842 show_stat = git_config_bool(var, value);
843 return 0;
845 if (!strcmp(var, "stash.showpatch")) {
846 show_patch = git_config_bool(var, value);
847 return 0;
849 if (!strcmp(var, "stash.showincludeuntracked")) {
850 show_include_untracked = git_config_bool(var, value);
851 return 0;
853 return git_diff_basic_config(var, value, cb);
856 static void diff_include_untracked(const struct stash_info *info, struct diff_options *diff_opt)
858 const struct object_id *oid[] = { &info->w_commit, &info->u_tree };
859 struct tree *tree[ARRAY_SIZE(oid)];
860 struct tree_desc tree_desc[ARRAY_SIZE(oid)];
861 struct unpack_trees_options unpack_tree_opt = { 0 };
862 int i;
864 for (i = 0; i < ARRAY_SIZE(oid); i++) {
865 tree[i] = parse_tree_indirect(oid[i]);
866 if (parse_tree(tree[i]) < 0)
867 die(_("failed to parse tree"));
868 init_tree_desc(&tree_desc[i], tree[i]->buffer, tree[i]->size);
871 unpack_tree_opt.head_idx = -1;
872 unpack_tree_opt.src_index = &the_index;
873 unpack_tree_opt.dst_index = &the_index;
874 unpack_tree_opt.merge = 1;
875 unpack_tree_opt.fn = stash_worktree_untracked_merge;
877 if (unpack_trees(ARRAY_SIZE(tree_desc), tree_desc, &unpack_tree_opt))
878 die(_("failed to unpack trees"));
880 do_diff_cache(&info->b_commit, diff_opt);
883 static int show_stash(int argc, const char **argv, const char *prefix)
885 int i;
886 int ret = -1;
887 struct stash_info info = STASH_INFO_INIT;
888 struct rev_info rev;
889 struct strvec stash_args = STRVEC_INIT;
890 struct strvec revision_args = STRVEC_INIT;
891 enum {
892 UNTRACKED_NONE,
893 UNTRACKED_INCLUDE,
894 UNTRACKED_ONLY
895 } show_untracked = show_include_untracked ? UNTRACKED_INCLUDE : UNTRACKED_NONE;
896 struct option options[] = {
897 OPT_SET_INT('u', "include-untracked", &show_untracked,
898 N_("include untracked files in the stash"),
899 UNTRACKED_INCLUDE),
900 OPT_SET_INT_F(0, "only-untracked", &show_untracked,
901 N_("only show untracked files in the stash"),
902 UNTRACKED_ONLY, PARSE_OPT_NONEG),
903 OPT_END()
905 int do_usage = 0;
907 init_diff_ui_defaults();
908 git_config(git_diff_ui_config, NULL);
909 repo_init_revisions(the_repository, &rev, prefix);
911 argc = parse_options(argc, argv, prefix, options, git_stash_show_usage,
912 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN_OPT |
913 PARSE_OPT_KEEP_DASHDASH);
915 strvec_push(&revision_args, argv[0]);
916 for (i = 1; i < argc; i++) {
917 if (argv[i][0] != '-')
918 strvec_push(&stash_args, argv[i]);
919 else
920 strvec_push(&revision_args, argv[i]);
923 if (get_stash_info(&info, stash_args.nr, stash_args.v))
924 goto cleanup;
927 * The config settings are applied only if there are not passed
928 * any options.
930 if (revision_args.nr == 1) {
931 if (show_stat)
932 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
934 if (show_patch)
935 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
937 if (!show_stat && !show_patch) {
938 ret = 0;
939 goto cleanup;
943 argc = setup_revisions(revision_args.nr, revision_args.v, &rev, NULL);
944 if (argc > 1)
945 goto usage;
946 if (!rev.diffopt.output_format) {
947 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
948 diff_setup_done(&rev.diffopt);
951 rev.diffopt.flags.recursive = 1;
952 setup_diff_pager(&rev.diffopt);
953 switch (show_untracked) {
954 case UNTRACKED_NONE:
955 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
956 break;
957 case UNTRACKED_ONLY:
958 if (info.has_u)
959 diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
960 break;
961 case UNTRACKED_INCLUDE:
962 if (info.has_u)
963 diff_include_untracked(&info, &rev.diffopt);
964 else
965 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
966 break;
968 log_tree_diff_flush(&rev);
970 ret = diff_result_code(&rev.diffopt, 0);
971 cleanup:
972 strvec_clear(&stash_args);
973 free_stash_info(&info);
974 release_revisions(&rev);
975 if (do_usage)
976 usage_with_options(git_stash_show_usage, options);
977 return ret;
978 usage:
979 do_usage = 1;
980 goto cleanup;
983 static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
984 int quiet)
986 if (!stash_msg)
987 stash_msg = "Created via \"git stash store\".";
989 if (update_ref(stash_msg, ref_stash, w_commit, NULL,
990 REF_FORCE_CREATE_REFLOG,
991 quiet ? UPDATE_REFS_QUIET_ON_ERR :
992 UPDATE_REFS_MSG_ON_ERR)) {
993 if (!quiet) {
994 fprintf_ln(stderr, _("Cannot update %s with %s"),
995 ref_stash, oid_to_hex(w_commit));
997 return -1;
1000 return 0;
1003 static int store_stash(int argc, const char **argv, const char *prefix)
1005 int quiet = 0;
1006 const char *stash_msg = NULL;
1007 struct object_id obj;
1008 struct object_context dummy;
1009 struct option options[] = {
1010 OPT__QUIET(&quiet, N_("be quiet")),
1011 OPT_STRING('m', "message", &stash_msg, "message",
1012 N_("stash message")),
1013 OPT_END()
1016 argc = parse_options(argc, argv, prefix, options,
1017 git_stash_store_usage,
1018 PARSE_OPT_KEEP_UNKNOWN_OPT);
1020 if (argc != 1) {
1021 if (!quiet)
1022 fprintf_ln(stderr, _("\"git stash store\" requires one "
1023 "<commit> argument"));
1024 return -1;
1027 if (get_oid_with_context(the_repository,
1028 argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
1029 &dummy)) {
1030 if (!quiet)
1031 fprintf_ln(stderr, _("Cannot update %s with %s"),
1032 ref_stash, argv[0]);
1033 return -1;
1036 return do_store_stash(&obj, stash_msg, quiet);
1039 static void add_pathspecs(struct strvec *args,
1040 const struct pathspec *ps) {
1041 int i;
1043 for (i = 0; i < ps->nr; i++)
1044 strvec_push(args, ps->items[i].original);
1048 * `untracked_files` will be filled with the names of untracked files.
1049 * The return value is:
1051 * = 0 if there are not any untracked files
1052 * > 0 if there are untracked files
1054 static int get_untracked_files(const struct pathspec *ps, int include_untracked,
1055 struct strbuf *untracked_files)
1057 int i;
1058 int found = 0;
1059 struct dir_struct dir = DIR_INIT;
1061 if (include_untracked != INCLUDE_ALL_FILES)
1062 setup_standard_excludes(&dir);
1064 fill_directory(&dir, the_repository->index, ps);
1065 for (i = 0; i < dir.nr; i++) {
1066 struct dir_entry *ent = dir.entries[i];
1067 found++;
1068 strbuf_addstr(untracked_files, ent->name);
1069 /* NUL-terminate: will be fed to update-index -z */
1070 strbuf_addch(untracked_files, '\0');
1073 dir_clear(&dir);
1074 return found;
1078 * The return value of `check_changes_tracked_files()` can be:
1080 * < 0 if there was an error
1081 * = 0 if there are no changes.
1082 * > 0 if there are changes.
1084 static int check_changes_tracked_files(const struct pathspec *ps)
1086 int result;
1087 struct rev_info rev;
1088 struct object_id dummy;
1089 int ret = 0;
1091 /* No initial commit. */
1092 if (repo_get_oid(the_repository, "HEAD", &dummy))
1093 return -1;
1095 if (repo_read_index(the_repository) < 0)
1096 return -1;
1098 repo_init_revisions(the_repository, &rev, NULL);
1099 copy_pathspec(&rev.prune_data, ps);
1101 rev.diffopt.flags.quick = 1;
1102 rev.diffopt.flags.ignore_submodules = 1;
1103 rev.abbrev = 0;
1105 add_head_to_pending(&rev);
1106 diff_setup_done(&rev.diffopt);
1108 result = run_diff_index(&rev, 1);
1109 if (diff_result_code(&rev.diffopt, result)) {
1110 ret = 1;
1111 goto done;
1114 result = run_diff_files(&rev, 0);
1115 if (diff_result_code(&rev.diffopt, result)) {
1116 ret = 1;
1117 goto done;
1120 done:
1121 release_revisions(&rev);
1122 return ret;
1126 * The function will fill `untracked_files` with the names of untracked files
1127 * It will return 1 if there were any changes and 0 if there were not.
1129 static int check_changes(const struct pathspec *ps, int include_untracked,
1130 struct strbuf *untracked_files)
1132 int ret = 0;
1133 if (check_changes_tracked_files(ps))
1134 ret = 1;
1136 if (include_untracked && get_untracked_files(ps, include_untracked,
1137 untracked_files))
1138 ret = 1;
1140 return ret;
1143 static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
1144 struct strbuf files)
1146 int ret = 0;
1147 struct strbuf untracked_msg = STRBUF_INIT;
1148 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1149 struct index_state istate = INDEX_STATE_INIT(the_repository);
1151 cp_upd_index.git_cmd = 1;
1152 strvec_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
1153 "--remove", "--stdin", NULL);
1154 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1155 stash_index_path.buf);
1157 strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
1158 if (pipe_command(&cp_upd_index, files.buf, files.len, NULL, 0,
1159 NULL, 0)) {
1160 ret = -1;
1161 goto done;
1164 if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
1165 NULL)) {
1166 ret = -1;
1167 goto done;
1170 if (commit_tree(untracked_msg.buf, untracked_msg.len,
1171 &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
1172 ret = -1;
1173 goto done;
1176 done:
1177 release_index(&istate);
1178 strbuf_release(&untracked_msg);
1179 remove_path(stash_index_path.buf);
1180 return ret;
1183 static int stash_staged(struct stash_info *info, struct strbuf *out_patch,
1184 int quiet)
1186 int ret = 0;
1187 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1188 struct index_state istate = INDEX_STATE_INIT(the_repository);
1190 if (write_index_as_tree(&info->w_tree, &istate, the_repository->index_file,
1191 0, NULL)) {
1192 ret = -1;
1193 goto done;
1196 cp_diff_tree.git_cmd = 1;
1197 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1198 oid_to_hex(&info->w_tree), "--", NULL);
1199 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1200 ret = -1;
1201 goto done;
1204 if (!out_patch->len) {
1205 if (!quiet)
1206 fprintf_ln(stderr, _("No staged changes"));
1207 ret = 1;
1210 done:
1211 release_index(&istate);
1212 return ret;
1215 static int stash_patch(struct stash_info *info, const struct pathspec *ps,
1216 struct strbuf *out_patch, int quiet)
1218 int ret = 0;
1219 struct child_process cp_read_tree = CHILD_PROCESS_INIT;
1220 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1221 struct index_state istate = INDEX_STATE_INIT(the_repository);
1222 char *old_index_env = NULL, *old_repo_index_file;
1224 remove_path(stash_index_path.buf);
1226 cp_read_tree.git_cmd = 1;
1227 strvec_pushl(&cp_read_tree.args, "read-tree", "HEAD", NULL);
1228 strvec_pushf(&cp_read_tree.env, "GIT_INDEX_FILE=%s",
1229 stash_index_path.buf);
1230 if (run_command(&cp_read_tree)) {
1231 ret = -1;
1232 goto done;
1235 /* Find out what the user wants. */
1236 old_repo_index_file = the_repository->index_file;
1237 the_repository->index_file = stash_index_path.buf;
1238 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
1239 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
1241 ret = !!run_add_p(the_repository, ADD_P_STASH, NULL, ps);
1243 the_repository->index_file = old_repo_index_file;
1244 if (old_index_env && *old_index_env)
1245 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
1246 else
1247 unsetenv(INDEX_ENVIRONMENT);
1248 FREE_AND_NULL(old_index_env);
1250 /* State of the working tree. */
1251 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1252 NULL)) {
1253 ret = -1;
1254 goto done;
1257 cp_diff_tree.git_cmd = 1;
1258 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1259 oid_to_hex(&info->w_tree), "--", NULL);
1260 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1261 ret = -1;
1262 goto done;
1265 if (!out_patch->len) {
1266 if (!quiet)
1267 fprintf_ln(stderr, _("No changes selected"));
1268 ret = 1;
1271 done:
1272 release_index(&istate);
1273 remove_path(stash_index_path.buf);
1274 return ret;
1277 static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
1279 int ret = 0;
1280 struct rev_info rev;
1281 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1282 struct strbuf diff_output = STRBUF_INIT;
1283 struct index_state istate = INDEX_STATE_INIT(the_repository);
1285 repo_init_revisions(the_repository, &rev, NULL);
1286 copy_pathspec(&rev.prune_data, ps);
1288 set_alternate_index_output(stash_index_path.buf);
1289 if (reset_tree(&info->i_tree, 0, 0)) {
1290 ret = -1;
1291 goto done;
1293 set_alternate_index_output(NULL);
1295 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1296 rev.diffopt.format_callback = add_diff_to_buf;
1297 rev.diffopt.format_callback_data = &diff_output;
1299 if (repo_read_index_preload(the_repository, &rev.diffopt.pathspec, 0) < 0) {
1300 ret = -1;
1301 goto done;
1304 add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1305 "");
1306 if (run_diff_index(&rev, 0)) {
1307 ret = -1;
1308 goto done;
1311 cp_upd_index.git_cmd = 1;
1312 strvec_pushl(&cp_upd_index.args, "update-index",
1313 "--ignore-skip-worktree-entries",
1314 "-z", "--add", "--remove", "--stdin", NULL);
1315 strvec_pushf(&cp_upd_index.env, "GIT_INDEX_FILE=%s",
1316 stash_index_path.buf);
1318 if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1319 NULL, 0, NULL, 0)) {
1320 ret = -1;
1321 goto done;
1324 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1325 NULL)) {
1326 ret = -1;
1327 goto done;
1330 done:
1331 release_index(&istate);
1332 release_revisions(&rev);
1333 strbuf_release(&diff_output);
1334 remove_path(stash_index_path.buf);
1335 return ret;
1338 static int do_create_stash(const struct pathspec *ps, struct strbuf *stash_msg_buf,
1339 int include_untracked, int patch_mode, int only_staged,
1340 struct stash_info *info, struct strbuf *patch,
1341 int quiet)
1343 int ret = 0;
1344 int flags = 0;
1345 int untracked_commit_option = 0;
1346 const char *head_short_sha1 = NULL;
1347 const char *branch_ref = NULL;
1348 const char *branch_name = "(no branch)";
1349 struct commit *head_commit = NULL;
1350 struct commit_list *parents = NULL;
1351 struct strbuf msg = STRBUF_INIT;
1352 struct strbuf commit_tree_label = STRBUF_INIT;
1353 struct strbuf untracked_files = STRBUF_INIT;
1355 prepare_fallback_ident("git stash", "git@stash");
1357 repo_read_index_preload(the_repository, NULL, 0);
1358 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1359 NULL, NULL, NULL) < 0) {
1360 ret = -1;
1361 goto done;
1364 if (repo_get_oid(the_repository, "HEAD", &info->b_commit)) {
1365 if (!quiet)
1366 fprintf_ln(stderr, _("You do not have "
1367 "the initial commit yet"));
1368 ret = -1;
1369 goto done;
1370 } else {
1371 head_commit = lookup_commit(the_repository, &info->b_commit);
1374 if (!check_changes(ps, include_untracked, &untracked_files)) {
1375 ret = 1;
1376 goto done;
1379 branch_ref = resolve_ref_unsafe("HEAD", 0, NULL, &flags);
1380 if (flags & REF_ISSYMREF)
1381 skip_prefix(branch_ref, "refs/heads/", &branch_name);
1382 head_short_sha1 = repo_find_unique_abbrev(the_repository,
1383 &head_commit->object.oid,
1384 DEFAULT_ABBREV);
1385 strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1386 pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1388 strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1389 commit_list_insert(head_commit, &parents);
1390 if (write_index_as_tree(&info->i_tree, &the_index, get_index_file(), 0,
1391 NULL) ||
1392 commit_tree(commit_tree_label.buf, commit_tree_label.len,
1393 &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1394 if (!quiet)
1395 fprintf_ln(stderr, _("Cannot save the current "
1396 "index state"));
1397 ret = -1;
1398 goto done;
1401 if (include_untracked) {
1402 if (save_untracked_files(info, &msg, untracked_files)) {
1403 if (!quiet)
1404 fprintf_ln(stderr, _("Cannot save "
1405 "the untracked files"));
1406 ret = -1;
1407 goto done;
1409 untracked_commit_option = 1;
1411 if (patch_mode) {
1412 ret = stash_patch(info, ps, patch, quiet);
1413 if (ret < 0) {
1414 if (!quiet)
1415 fprintf_ln(stderr, _("Cannot save the current "
1416 "worktree state"));
1417 goto done;
1418 } else if (ret > 0) {
1419 goto done;
1421 } else if (only_staged) {
1422 ret = stash_staged(info, patch, quiet);
1423 if (ret < 0) {
1424 if (!quiet)
1425 fprintf_ln(stderr, _("Cannot save the current "
1426 "staged state"));
1427 goto done;
1428 } else if (ret > 0) {
1429 goto done;
1431 } else {
1432 if (stash_working_tree(info, ps)) {
1433 if (!quiet)
1434 fprintf_ln(stderr, _("Cannot save the current "
1435 "worktree state"));
1436 ret = -1;
1437 goto done;
1441 if (!stash_msg_buf->len)
1442 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1443 else
1444 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1447 * `parents` will be empty after calling `commit_tree()`, so there is
1448 * no need to call `free_commit_list()`
1450 parents = NULL;
1451 if (untracked_commit_option)
1452 commit_list_insert(lookup_commit(the_repository,
1453 &info->u_commit),
1454 &parents);
1455 commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1456 &parents);
1457 commit_list_insert(head_commit, &parents);
1459 if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1460 parents, &info->w_commit, NULL, NULL)) {
1461 if (!quiet)
1462 fprintf_ln(stderr, _("Cannot record "
1463 "working tree state"));
1464 ret = -1;
1465 goto done;
1468 done:
1469 strbuf_release(&commit_tree_label);
1470 strbuf_release(&msg);
1471 strbuf_release(&untracked_files);
1472 return ret;
1475 static int create_stash(int argc, const char **argv, const char *prefix UNUSED)
1477 int ret;
1478 struct strbuf stash_msg_buf = STRBUF_INIT;
1479 struct stash_info info = STASH_INFO_INIT;
1480 struct pathspec ps;
1482 /* Starting with argv[1], since argv[0] is "create" */
1483 strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
1485 memset(&ps, 0, sizeof(ps));
1486 if (!check_changes_tracked_files(&ps))
1487 return 0;
1489 ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, 0, &info,
1490 NULL, 0);
1491 if (!ret)
1492 printf_ln("%s", oid_to_hex(&info.w_commit));
1494 free_stash_info(&info);
1495 strbuf_release(&stash_msg_buf);
1496 return ret;
1499 static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int quiet,
1500 int keep_index, int patch_mode, int include_untracked, int only_staged)
1502 int ret = 0;
1503 struct stash_info info = STASH_INFO_INIT;
1504 struct strbuf patch = STRBUF_INIT;
1505 struct strbuf stash_msg_buf = STRBUF_INIT;
1506 struct strbuf untracked_files = STRBUF_INIT;
1508 if (patch_mode && keep_index == -1)
1509 keep_index = 1;
1511 if (patch_mode && include_untracked) {
1512 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1513 " or --all at the same time"));
1514 ret = -1;
1515 goto done;
1518 /* --patch overrides --staged */
1519 if (patch_mode)
1520 only_staged = 0;
1522 if (only_staged && include_untracked) {
1523 fprintf_ln(stderr, _("Can't use --staged and --include-untracked"
1524 " or --all at the same time"));
1525 ret = -1;
1526 goto done;
1529 repo_read_index_preload(the_repository, NULL, 0);
1530 if (!include_untracked && ps->nr) {
1531 int i;
1532 char *ps_matched = xcalloc(ps->nr, 1);
1534 /* TODO: audit for interaction with sparse-index. */
1535 ensure_full_index(&the_index);
1536 for (i = 0; i < the_index.cache_nr; i++)
1537 ce_path_match(&the_index, the_index.cache[i], ps,
1538 ps_matched);
1540 if (report_path_error(ps_matched, ps)) {
1541 fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1542 ret = -1;
1543 free(ps_matched);
1544 goto done;
1546 free(ps_matched);
1549 if (repo_refresh_and_write_index(the_repository, REFRESH_QUIET, 0, 0,
1550 NULL, NULL, NULL)) {
1551 ret = -1;
1552 goto done;
1555 if (!check_changes(ps, include_untracked, &untracked_files)) {
1556 if (!quiet)
1557 printf_ln(_("No local changes to save"));
1558 goto done;
1561 if (!reflog_exists(ref_stash) && do_clear_stash()) {
1562 ret = -1;
1563 if (!quiet)
1564 fprintf_ln(stderr, _("Cannot initialize stash"));
1565 goto done;
1568 if (stash_msg)
1569 strbuf_addstr(&stash_msg_buf, stash_msg);
1570 if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode, only_staged,
1571 &info, &patch, quiet)) {
1572 ret = -1;
1573 goto done;
1576 if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1577 ret = -1;
1578 if (!quiet)
1579 fprintf_ln(stderr, _("Cannot save the current status"));
1580 goto done;
1583 if (!quiet)
1584 printf_ln(_("Saved working directory and index state %s"),
1585 stash_msg_buf.buf);
1587 if (!(patch_mode || only_staged)) {
1588 if (include_untracked && !ps->nr) {
1589 struct child_process cp = CHILD_PROCESS_INIT;
1591 cp.git_cmd = 1;
1592 if (startup_info->original_cwd) {
1593 cp.dir = startup_info->original_cwd;
1594 strvec_pushf(&cp.env, "%s=%s",
1595 GIT_WORK_TREE_ENVIRONMENT,
1596 the_repository->worktree);
1598 strvec_pushl(&cp.args, "clean", "--force",
1599 "--quiet", "-d", ":/", NULL);
1600 if (include_untracked == INCLUDE_ALL_FILES)
1601 strvec_push(&cp.args, "-x");
1602 if (run_command(&cp)) {
1603 ret = -1;
1604 goto done;
1607 discard_index(&the_index);
1608 if (ps->nr) {
1609 struct child_process cp_add = CHILD_PROCESS_INIT;
1610 struct child_process cp_diff = CHILD_PROCESS_INIT;
1611 struct child_process cp_apply = CHILD_PROCESS_INIT;
1612 struct strbuf out = STRBUF_INIT;
1614 cp_add.git_cmd = 1;
1615 strvec_push(&cp_add.args, "add");
1616 if (!include_untracked)
1617 strvec_push(&cp_add.args, "-u");
1618 if (include_untracked == INCLUDE_ALL_FILES)
1619 strvec_push(&cp_add.args, "--force");
1620 strvec_push(&cp_add.args, "--");
1621 add_pathspecs(&cp_add.args, ps);
1622 if (run_command(&cp_add)) {
1623 ret = -1;
1624 goto done;
1627 cp_diff.git_cmd = 1;
1628 strvec_pushl(&cp_diff.args, "diff-index", "-p",
1629 "--cached", "--binary", "HEAD", "--",
1630 NULL);
1631 add_pathspecs(&cp_diff.args, ps);
1632 if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1633 ret = -1;
1634 goto done;
1637 cp_apply.git_cmd = 1;
1638 strvec_pushl(&cp_apply.args, "apply", "--index",
1639 "-R", NULL);
1640 if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1641 NULL, 0)) {
1642 ret = -1;
1643 goto done;
1645 } else {
1646 struct child_process cp = CHILD_PROCESS_INIT;
1647 cp.git_cmd = 1;
1648 /* BUG: this nukes untracked files in the way */
1649 strvec_pushl(&cp.args, "reset", "--hard", "-q",
1650 "--no-recurse-submodules", NULL);
1651 if (run_command(&cp)) {
1652 ret = -1;
1653 goto done;
1657 if (keep_index == 1 && !is_null_oid(&info.i_tree)) {
1658 struct child_process cp = CHILD_PROCESS_INIT;
1660 cp.git_cmd = 1;
1661 strvec_pushl(&cp.args, "checkout", "--no-overlay",
1662 oid_to_hex(&info.i_tree), "--", NULL);
1663 if (!ps->nr)
1664 strvec_push(&cp.args, ":/");
1665 else
1666 add_pathspecs(&cp.args, ps);
1667 if (run_command(&cp)) {
1668 ret = -1;
1669 goto done;
1672 goto done;
1673 } else {
1674 struct child_process cp = CHILD_PROCESS_INIT;
1676 cp.git_cmd = 1;
1677 strvec_pushl(&cp.args, "apply", "-R", NULL);
1679 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1680 if (!quiet)
1681 fprintf_ln(stderr, _("Cannot remove "
1682 "worktree changes"));
1683 ret = -1;
1684 goto done;
1687 if (keep_index < 1) {
1688 struct child_process cp = CHILD_PROCESS_INIT;
1690 cp.git_cmd = 1;
1691 strvec_pushl(&cp.args, "reset", "-q", "--refresh", "--",
1692 NULL);
1693 add_pathspecs(&cp.args, ps);
1694 if (run_command(&cp)) {
1695 ret = -1;
1696 goto done;
1699 goto done;
1702 done:
1703 strbuf_release(&patch);
1704 free_stash_info(&info);
1705 strbuf_release(&stash_msg_buf);
1706 strbuf_release(&untracked_files);
1707 return ret;
1710 static int push_stash(int argc, const char **argv, const char *prefix,
1711 int push_assumed)
1713 int force_assume = 0;
1714 int keep_index = -1;
1715 int only_staged = 0;
1716 int patch_mode = 0;
1717 int include_untracked = 0;
1718 int quiet = 0;
1719 int pathspec_file_nul = 0;
1720 const char *stash_msg = NULL;
1721 const char *pathspec_from_file = NULL;
1722 struct pathspec ps;
1723 struct option options[] = {
1724 OPT_BOOL('k', "keep-index", &keep_index,
1725 N_("keep index")),
1726 OPT_BOOL('S', "staged", &only_staged,
1727 N_("stash staged changes only")),
1728 OPT_BOOL('p', "patch", &patch_mode,
1729 N_("stash in patch mode")),
1730 OPT__QUIET(&quiet, N_("quiet mode")),
1731 OPT_BOOL('u', "include-untracked", &include_untracked,
1732 N_("include untracked files in stash")),
1733 OPT_SET_INT('a', "all", &include_untracked,
1734 N_("include ignore files"), 2),
1735 OPT_STRING('m', "message", &stash_msg, N_("message"),
1736 N_("stash message")),
1737 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1738 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1739 OPT_END()
1741 int ret;
1743 if (argc) {
1744 force_assume = !strcmp(argv[0], "-p");
1745 argc = parse_options(argc, argv, prefix, options,
1746 push_assumed ? git_stash_usage :
1747 git_stash_push_usage,
1748 PARSE_OPT_KEEP_DASHDASH);
1751 if (argc) {
1752 if (!strcmp(argv[0], "--")) {
1753 argc--;
1754 argv++;
1755 } else if (push_assumed && !force_assume) {
1756 die("subcommand wasn't specified; 'push' can't be assumed due to unexpected token '%s'",
1757 argv[0]);
1761 parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1762 prefix, argv);
1764 if (pathspec_from_file) {
1765 if (patch_mode)
1766 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1768 if (only_staged)
1769 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--staged");
1771 if (ps.nr)
1772 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1774 parse_pathspec_file(&ps, 0,
1775 PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1776 prefix, pathspec_from_file, pathspec_file_nul);
1777 } else if (pathspec_file_nul) {
1778 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1781 ret = do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
1782 include_untracked, only_staged);
1783 clear_pathspec(&ps);
1784 return ret;
1787 static int push_stash_unassumed(int argc, const char **argv, const char *prefix)
1789 return push_stash(argc, argv, prefix, 0);
1792 static int save_stash(int argc, const char **argv, const char *prefix)
1794 int keep_index = -1;
1795 int only_staged = 0;
1796 int patch_mode = 0;
1797 int include_untracked = 0;
1798 int quiet = 0;
1799 int ret = 0;
1800 const char *stash_msg = NULL;
1801 struct pathspec ps;
1802 struct strbuf stash_msg_buf = STRBUF_INIT;
1803 struct option options[] = {
1804 OPT_BOOL('k', "keep-index", &keep_index,
1805 N_("keep index")),
1806 OPT_BOOL('S', "staged", &only_staged,
1807 N_("stash staged changes only")),
1808 OPT_BOOL('p', "patch", &patch_mode,
1809 N_("stash in patch mode")),
1810 OPT__QUIET(&quiet, N_("quiet mode")),
1811 OPT_BOOL('u', "include-untracked", &include_untracked,
1812 N_("include untracked files in stash")),
1813 OPT_SET_INT('a', "all", &include_untracked,
1814 N_("include ignore files"), 2),
1815 OPT_STRING('m', "message", &stash_msg, "message",
1816 N_("stash message")),
1817 OPT_END()
1820 argc = parse_options(argc, argv, prefix, options,
1821 git_stash_save_usage,
1822 PARSE_OPT_KEEP_DASHDASH);
1824 if (argc)
1825 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
1827 memset(&ps, 0, sizeof(ps));
1828 ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
1829 patch_mode, include_untracked, only_staged);
1831 strbuf_release(&stash_msg_buf);
1832 return ret;
1835 int cmd_stash(int argc, const char **argv, const char *prefix)
1837 pid_t pid = getpid();
1838 const char *index_file;
1839 struct strvec args = STRVEC_INIT;
1840 parse_opt_subcommand_fn *fn = NULL;
1841 struct option options[] = {
1842 OPT_SUBCOMMAND("apply", &fn, apply_stash),
1843 OPT_SUBCOMMAND("clear", &fn, clear_stash),
1844 OPT_SUBCOMMAND("drop", &fn, drop_stash),
1845 OPT_SUBCOMMAND("pop", &fn, pop_stash),
1846 OPT_SUBCOMMAND("branch", &fn, branch_stash),
1847 OPT_SUBCOMMAND("list", &fn, list_stash),
1848 OPT_SUBCOMMAND("show", &fn, show_stash),
1849 OPT_SUBCOMMAND("store", &fn, store_stash),
1850 OPT_SUBCOMMAND("create", &fn, create_stash),
1851 OPT_SUBCOMMAND("push", &fn, push_stash_unassumed),
1852 OPT_SUBCOMMAND_F("save", &fn, save_stash, PARSE_OPT_NOCOMPLETE),
1853 OPT_END()
1856 git_config(git_stash_config, NULL);
1858 argc = parse_options(argc, argv, prefix, options, git_stash_usage,
1859 PARSE_OPT_SUBCOMMAND_OPTIONAL |
1860 PARSE_OPT_KEEP_UNKNOWN_OPT |
1861 PARSE_OPT_KEEP_DASHDASH);
1863 prepare_repo_settings(the_repository);
1864 the_repository->settings.command_requires_full_index = 0;
1866 index_file = get_index_file();
1867 strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
1868 (uintmax_t)pid);
1870 if (fn)
1871 return !!fn(argc, argv, prefix);
1872 else if (!argc)
1873 return !!push_stash_unassumed(0, NULL, prefix);
1875 /* Assume 'stash push' */
1876 strvec_push(&args, "push");
1877 strvec_pushv(&args, argv);
1878 return !!push_stash(args.nr, args.v, prefix, 1);