]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/stash.c
Merge branch 'ab/string-list-count-in-size-t'
[thirdparty/git.git] / builtin / stash.c
1 #define USE_THE_INDEX_COMPATIBILITY_MACROS
2 #include "builtin.h"
3 #include "config.h"
4 #include "parse-options.h"
5 #include "refs.h"
6 #include "lockfile.h"
7 #include "cache-tree.h"
8 #include "unpack-trees.h"
9 #include "merge-recursive.h"
10 #include "strvec.h"
11 #include "run-command.h"
12 #include "dir.h"
13 #include "entry.h"
14 #include "rerere.h"
15 #include "revision.h"
16 #include "log-tree.h"
17 #include "diffcore.h"
18 #include "exec-cmd.h"
19 #include "entry.h"
20 #include "reflog.h"
21
22 #define INCLUDE_ALL_FILES 2
23
24 static const char * const git_stash_usage[] = {
25 N_("git stash list [<options>]"),
26 N_("git stash show [<options>] [<stash>]"),
27 N_("git stash drop [-q|--quiet] [<stash>]"),
28 N_("git stash ( pop | apply ) [--index] [-q|--quiet] [<stash>]"),
29 N_("git stash branch <branchname> [<stash>]"),
30 "git stash clear",
31 N_("git stash [push [-p|--patch] [-S|--staged] [-k|--[no-]keep-index] [-q|--quiet]\n"
32 " [-u|--include-untracked] [-a|--all] [-m|--message <message>]\n"
33 " [--pathspec-from-file=<file> [--pathspec-file-nul]]\n"
34 " [--] [<pathspec>...]]"),
35 N_("git stash save [-p|--patch] [-S|--staged] [-k|--[no-]keep-index] [-q|--quiet]\n"
36 " [-u|--include-untracked] [-a|--all] [<message>]"),
37 NULL
38 };
39
40 static const char * const git_stash_list_usage[] = {
41 N_("git stash list [<options>]"),
42 NULL
43 };
44
45 static const char * const git_stash_show_usage[] = {
46 N_("git stash show [<options>] [<stash>]"),
47 NULL
48 };
49
50 static const char * const git_stash_drop_usage[] = {
51 N_("git stash drop [-q|--quiet] [<stash>]"),
52 NULL
53 };
54
55 static const char * const git_stash_pop_usage[] = {
56 N_("git stash pop [--index] [-q|--quiet] [<stash>]"),
57 NULL
58 };
59
60 static const char * const git_stash_apply_usage[] = {
61 N_("git stash apply [--index] [-q|--quiet] [<stash>]"),
62 NULL
63 };
64
65 static const char * const git_stash_branch_usage[] = {
66 N_("git stash branch <branchname> [<stash>]"),
67 NULL
68 };
69
70 static const char * const git_stash_clear_usage[] = {
71 "git stash clear",
72 NULL
73 };
74
75 static const char * const git_stash_store_usage[] = {
76 N_("git stash store [-m|--message <message>] [-q|--quiet] <commit>"),
77 NULL
78 };
79
80 static const char * const git_stash_push_usage[] = {
81 N_("git stash [push [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
82 " [-u|--include-untracked] [-a|--all] [-m|--message <message>]\n"
83 " [--] [<pathspec>...]]"),
84 NULL
85 };
86
87 static const char * const git_stash_save_usage[] = {
88 N_("git stash save [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
89 " [-u|--include-untracked] [-a|--all] [<message>]"),
90 NULL
91 };
92
93 static const char ref_stash[] = "refs/stash";
94 static struct strbuf stash_index_path = STRBUF_INIT;
95
96 /*
97 * w_commit is set to the commit containing the working tree
98 * b_commit is set to the base commit
99 * i_commit is set to the commit containing the index tree
100 * u_commit is set to the commit containing the untracked files tree
101 * w_tree is set to the working tree
102 * b_tree is set to the base tree
103 * i_tree is set to the index tree
104 * u_tree is set to the untracked files tree
105 */
106 struct stash_info {
107 struct object_id w_commit;
108 struct object_id b_commit;
109 struct object_id i_commit;
110 struct object_id u_commit;
111 struct object_id w_tree;
112 struct object_id b_tree;
113 struct object_id i_tree;
114 struct object_id u_tree;
115 struct strbuf revision;
116 int is_stash_ref;
117 int has_u;
118 };
119
120 static void free_stash_info(struct stash_info *info)
121 {
122 strbuf_release(&info->revision);
123 }
124
125 static void assert_stash_like(struct stash_info *info, const char *revision)
126 {
127 if (get_oidf(&info->b_commit, "%s^1", revision) ||
128 get_oidf(&info->w_tree, "%s:", revision) ||
129 get_oidf(&info->b_tree, "%s^1:", revision) ||
130 get_oidf(&info->i_tree, "%s^2:", revision))
131 die(_("'%s' is not a stash-like commit"), revision);
132 }
133
134 static int get_stash_info(struct stash_info *info, int argc, const char **argv)
135 {
136 int ret;
137 char *end_of_rev;
138 char *expanded_ref;
139 const char *revision;
140 const char *commit = NULL;
141 struct object_id dummy;
142 struct strbuf symbolic = STRBUF_INIT;
143
144 if (argc > 1) {
145 int i;
146 struct strbuf refs_msg = STRBUF_INIT;
147
148 for (i = 0; i < argc; i++)
149 strbuf_addf(&refs_msg, " '%s'", argv[i]);
150
151 fprintf_ln(stderr, _("Too many revisions specified:%s"),
152 refs_msg.buf);
153 strbuf_release(&refs_msg);
154
155 return -1;
156 }
157
158 if (argc == 1)
159 commit = argv[0];
160
161 strbuf_init(&info->revision, 0);
162 if (!commit) {
163 if (!ref_exists(ref_stash)) {
164 free_stash_info(info);
165 fprintf_ln(stderr, _("No stash entries found."));
166 return -1;
167 }
168
169 strbuf_addf(&info->revision, "%s@{0}", ref_stash);
170 } else if (strspn(commit, "0123456789") == strlen(commit)) {
171 strbuf_addf(&info->revision, "%s@{%s}", ref_stash, commit);
172 } else {
173 strbuf_addstr(&info->revision, commit);
174 }
175
176 revision = info->revision.buf;
177
178 if (get_oid(revision, &info->w_commit)) {
179 error(_("%s is not a valid reference"), revision);
180 free_stash_info(info);
181 return -1;
182 }
183
184 assert_stash_like(info, revision);
185
186 info->has_u = !get_oidf(&info->u_tree, "%s^3:", revision);
187
188 end_of_rev = strchrnul(revision, '@');
189 strbuf_add(&symbolic, revision, end_of_rev - revision);
190
191 ret = dwim_ref(symbolic.buf, symbolic.len, &dummy, &expanded_ref, 0);
192 strbuf_release(&symbolic);
193 switch (ret) {
194 case 0: /* Not found, but valid ref */
195 info->is_stash_ref = 0;
196 break;
197 case 1:
198 info->is_stash_ref = !strcmp(expanded_ref, ref_stash);
199 break;
200 default: /* Invalid or ambiguous */
201 free_stash_info(info);
202 }
203
204 free(expanded_ref);
205 return !(ret == 0 || ret == 1);
206 }
207
208 static int do_clear_stash(void)
209 {
210 struct object_id obj;
211 if (get_oid(ref_stash, &obj))
212 return 0;
213
214 return delete_ref(NULL, ref_stash, &obj, 0);
215 }
216
217 static int clear_stash(int argc, const char **argv, const char *prefix)
218 {
219 struct option options[] = {
220 OPT_END()
221 };
222
223 argc = parse_options(argc, argv, prefix, options,
224 git_stash_clear_usage,
225 PARSE_OPT_STOP_AT_NON_OPTION);
226
227 if (argc)
228 return error(_("git stash clear with arguments is "
229 "unimplemented"));
230
231 return do_clear_stash();
232 }
233
234 static int reset_tree(struct object_id *i_tree, int update, int reset)
235 {
236 int nr_trees = 1;
237 struct unpack_trees_options opts;
238 struct tree_desc t[MAX_UNPACK_TREES];
239 struct tree *tree;
240 struct lock_file lock_file = LOCK_INIT;
241
242 read_cache_preload(NULL);
243 if (refresh_cache(REFRESH_QUIET))
244 return -1;
245
246 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
247
248 memset(&opts, 0, sizeof(opts));
249
250 tree = parse_tree_indirect(i_tree);
251 if (parse_tree(tree))
252 return -1;
253
254 init_tree_desc(t, tree->buffer, tree->size);
255
256 opts.head_idx = 1;
257 opts.src_index = &the_index;
258 opts.dst_index = &the_index;
259 opts.merge = 1;
260 opts.reset = reset ? UNPACK_RESET_PROTECT_UNTRACKED : 0;
261 opts.update = update;
262 if (update)
263 opts.preserve_ignored = 0; /* FIXME: !overwrite_ignore */
264 opts.fn = oneway_merge;
265
266 if (unpack_trees(nr_trees, t, &opts))
267 return -1;
268
269 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
270 return error(_("unable to write new index file"));
271
272 return 0;
273 }
274
275 static int diff_tree_binary(struct strbuf *out, struct object_id *w_commit)
276 {
277 struct child_process cp = CHILD_PROCESS_INIT;
278 const char *w_commit_hex = oid_to_hex(w_commit);
279
280 /*
281 * Diff-tree would not be very hard to replace with a native function,
282 * however it should be done together with apply_cached.
283 */
284 cp.git_cmd = 1;
285 strvec_pushl(&cp.args, "diff-tree", "--binary", NULL);
286 strvec_pushf(&cp.args, "%s^2^..%s^2", w_commit_hex, w_commit_hex);
287
288 return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
289 }
290
291 static int apply_cached(struct strbuf *out)
292 {
293 struct child_process cp = CHILD_PROCESS_INIT;
294
295 /*
296 * Apply currently only reads either from stdin or a file, thus
297 * apply_all_patches would have to be updated to optionally take a
298 * buffer.
299 */
300 cp.git_cmd = 1;
301 strvec_pushl(&cp.args, "apply", "--cached", NULL);
302 return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
303 }
304
305 static int reset_head(void)
306 {
307 struct child_process cp = CHILD_PROCESS_INIT;
308
309 /*
310 * Reset is overall quite simple, however there is no current public
311 * API for resetting.
312 */
313 cp.git_cmd = 1;
314 strvec_push(&cp.args, "reset");
315
316 return run_command(&cp);
317 }
318
319 static int is_path_a_directory(const char *path)
320 {
321 /*
322 * This function differs from abspath.c:is_directory() in that
323 * here we use lstat() instead of stat(); we do not want to
324 * follow symbolic links here.
325 */
326 struct stat st;
327 return (!lstat(path, &st) && S_ISDIR(st.st_mode));
328 }
329
330 static void add_diff_to_buf(struct diff_queue_struct *q,
331 struct diff_options *options,
332 void *data)
333 {
334 int i;
335
336 for (i = 0; i < q->nr; i++) {
337 if (is_path_a_directory(q->queue[i]->one->path))
338 continue;
339
340 strbuf_addstr(data, q->queue[i]->one->path);
341
342 /* NUL-terminate: will be fed to update-index -z */
343 strbuf_addch(data, '\0');
344 }
345 }
346
347 static int restore_untracked(struct object_id *u_tree)
348 {
349 int res;
350 struct child_process cp = CHILD_PROCESS_INIT;
351
352 /*
353 * We need to run restore files from a given index, but without
354 * affecting the current index, so we use GIT_INDEX_FILE with
355 * run_command to fork processes that will not interfere.
356 */
357 cp.git_cmd = 1;
358 strvec_push(&cp.args, "read-tree");
359 strvec_push(&cp.args, oid_to_hex(u_tree));
360 strvec_pushf(&cp.env_array, "GIT_INDEX_FILE=%s",
361 stash_index_path.buf);
362 if (run_command(&cp)) {
363 remove_path(stash_index_path.buf);
364 return -1;
365 }
366
367 child_process_init(&cp);
368 cp.git_cmd = 1;
369 strvec_pushl(&cp.args, "checkout-index", "--all", NULL);
370 strvec_pushf(&cp.env_array, "GIT_INDEX_FILE=%s",
371 stash_index_path.buf);
372
373 res = run_command(&cp);
374 remove_path(stash_index_path.buf);
375 return res;
376 }
377
378 static void unstage_changes_unless_new(struct object_id *orig_tree)
379 {
380 /*
381 * When we enter this function, there has been a clean merge of
382 * relevant trees, and the merge logic always stages whatever merges
383 * cleanly. We want to unstage those changes, unless it corresponds
384 * to a file that didn't exist as of orig_tree.
385 *
386 * However, if any SKIP_WORKTREE path is modified relative to
387 * orig_tree, then we want to clear the SKIP_WORKTREE bit and write
388 * it to the worktree before unstaging.
389 */
390
391 struct checkout state = CHECKOUT_INIT;
392 struct diff_options diff_opts;
393 struct lock_file lock = LOCK_INIT;
394 int i;
395
396 /* If any entries have skip_worktree set, we'll have to check 'em out */
397 state.force = 1;
398 state.quiet = 1;
399 state.refresh_cache = 1;
400 state.istate = &the_index;
401
402 /*
403 * Step 1: get a difference between orig_tree (which corresponding
404 * to the index before a merge was run) and the current index
405 * (reflecting the changes brought in by the merge).
406 */
407 diff_setup(&diff_opts);
408 diff_opts.flags.recursive = 1;
409 diff_opts.detect_rename = 0;
410 diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
411 diff_setup_done(&diff_opts);
412
413 do_diff_cache(orig_tree, &diff_opts);
414 diffcore_std(&diff_opts);
415
416 /* Iterate over the paths that changed due to the merge... */
417 for (i = 0; i < diff_queued_diff.nr; i++) {
418 struct diff_filepair *p;
419 struct cache_entry *ce;
420 int pos;
421
422 /* Look up the path's position in the current index. */
423 p = diff_queued_diff.queue[i];
424 pos = index_name_pos(&the_index, p->two->path,
425 strlen(p->two->path));
426
427 /*
428 * Step 2: Place changes in the working tree
429 *
430 * Stash is about restoring changes *to the working tree*.
431 * So if the merge successfully got a new version of some
432 * path, but left it out of the working tree, then clear the
433 * SKIP_WORKTREE bit and write it to the working tree.
434 */
435 if (pos >= 0 && ce_skip_worktree(active_cache[pos])) {
436 struct stat st;
437
438 ce = active_cache[pos];
439 if (!lstat(ce->name, &st)) {
440 /* Conflicting path present; relocate it */
441 struct strbuf new_path = STRBUF_INIT;
442 int fd;
443
444 strbuf_addf(&new_path,
445 "%s.stash.XXXXXX", ce->name);
446 fd = xmkstemp(new_path.buf);
447 close(fd);
448 printf(_("WARNING: Untracked file in way of "
449 "tracked file! Renaming\n "
450 " %s -> %s\n"
451 " to make room.\n"),
452 ce->name, new_path.buf);
453 if (rename(ce->name, new_path.buf))
454 die("Failed to move %s to %s\n",
455 ce->name, new_path.buf);
456 strbuf_release(&new_path);
457 }
458 checkout_entry(ce, &state, NULL, NULL);
459 ce->ce_flags &= ~CE_SKIP_WORKTREE;
460 }
461
462 /*
463 * Step 3: "unstage" changes, as long as they are still tracked
464 */
465 if (p->one->oid_valid) {
466 /*
467 * Path existed in orig_tree; restore index entry
468 * from that tree in order to "unstage" the changes.
469 */
470 int option = ADD_CACHE_OK_TO_REPLACE;
471 if (pos < 0)
472 option = ADD_CACHE_OK_TO_ADD;
473
474 ce = make_cache_entry(&the_index,
475 p->one->mode,
476 &p->one->oid,
477 p->one->path,
478 0, 0);
479 add_index_entry(&the_index, ce, option);
480 }
481 }
482 diff_flush(&diff_opts);
483
484 /*
485 * Step 4: write the new index to disk
486 */
487 repo_hold_locked_index(the_repository, &lock, LOCK_DIE_ON_ERROR);
488 if (write_locked_index(&the_index, &lock,
489 COMMIT_LOCK | SKIP_IF_UNCHANGED))
490 die(_("Unable to write index."));
491 }
492
493 static int do_apply_stash(const char *prefix, struct stash_info *info,
494 int index, int quiet)
495 {
496 int ret;
497 int has_index = index;
498 struct merge_options o;
499 struct object_id c_tree;
500 struct object_id index_tree;
501 struct commit *result;
502 const struct object_id *bases[1];
503
504 read_cache_preload(NULL);
505 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0))
506 return -1;
507
508 if (write_cache_as_tree(&c_tree, 0, NULL))
509 return error(_("cannot apply a stash in the middle of a merge"));
510
511 if (index) {
512 if (oideq(&info->b_tree, &info->i_tree) ||
513 oideq(&c_tree, &info->i_tree)) {
514 has_index = 0;
515 } else {
516 struct strbuf out = STRBUF_INIT;
517
518 if (diff_tree_binary(&out, &info->w_commit)) {
519 strbuf_release(&out);
520 return error(_("could not generate diff %s^!."),
521 oid_to_hex(&info->w_commit));
522 }
523
524 ret = apply_cached(&out);
525 strbuf_release(&out);
526 if (ret)
527 return error(_("conflicts in index. "
528 "Try without --index."));
529
530 discard_cache();
531 read_cache();
532 if (write_cache_as_tree(&index_tree, 0, NULL))
533 return error(_("could not save index tree"));
534
535 reset_head();
536 discard_cache();
537 read_cache();
538 }
539 }
540
541 init_merge_options(&o, the_repository);
542
543 o.branch1 = "Updated upstream";
544 o.branch2 = "Stashed changes";
545
546 if (oideq(&info->b_tree, &c_tree))
547 o.branch1 = "Version stash was based on";
548
549 if (quiet)
550 o.verbosity = 0;
551
552 if (o.verbosity >= 3)
553 printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
554
555 bases[0] = &info->b_tree;
556
557 ret = merge_recursive_generic(&o, &c_tree, &info->w_tree, 1, bases,
558 &result);
559 if (ret) {
560 rerere(0);
561
562 if (index)
563 fprintf_ln(stderr, _("Index was not unstashed."));
564
565 goto restore_untracked;
566 }
567
568 if (has_index) {
569 if (reset_tree(&index_tree, 0, 0))
570 ret = -1;
571 } else {
572 unstage_changes_unless_new(&c_tree);
573 }
574
575 restore_untracked:
576 if (info->has_u && restore_untracked(&info->u_tree))
577 ret = error(_("could not restore untracked files from stash"));
578
579 if (!quiet) {
580 struct child_process cp = CHILD_PROCESS_INIT;
581
582 /*
583 * Status is quite simple and could be replaced with calls to
584 * wt_status in the future, but it adds complexities which may
585 * require more tests.
586 */
587 cp.git_cmd = 1;
588 cp.dir = prefix;
589 strvec_pushf(&cp.env_array, GIT_WORK_TREE_ENVIRONMENT"=%s",
590 absolute_path(get_git_work_tree()));
591 strvec_pushf(&cp.env_array, GIT_DIR_ENVIRONMENT"=%s",
592 absolute_path(get_git_dir()));
593 strvec_push(&cp.args, "status");
594 run_command(&cp);
595 }
596
597 return ret;
598 }
599
600 static int apply_stash(int argc, const char **argv, const char *prefix)
601 {
602 int ret;
603 int quiet = 0;
604 int index = 0;
605 struct stash_info info;
606 struct option options[] = {
607 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
608 OPT_BOOL(0, "index", &index,
609 N_("attempt to recreate the index")),
610 OPT_END()
611 };
612
613 argc = parse_options(argc, argv, prefix, options,
614 git_stash_apply_usage, 0);
615
616 if (get_stash_info(&info, argc, argv))
617 return -1;
618
619 ret = do_apply_stash(prefix, &info, index, quiet);
620 free_stash_info(&info);
621 return ret;
622 }
623
624 static int reject_reflog_ent(struct object_id *ooid, struct object_id *noid,
625 const char *email, timestamp_t timestamp, int tz,
626 const char *message, void *cb_data)
627 {
628 return 1;
629 }
630
631 static int reflog_is_empty(const char *refname)
632 {
633 return !for_each_reflog_ent(refname, reject_reflog_ent, NULL);
634 }
635
636 static int do_drop_stash(struct stash_info *info, int quiet)
637 {
638 if (!reflog_delete(info->revision.buf,
639 EXPIRE_REFLOGS_REWRITE | EXPIRE_REFLOGS_UPDATE_REF,
640 0)) {
641 if (!quiet)
642 printf_ln(_("Dropped %s (%s)"), info->revision.buf,
643 oid_to_hex(&info->w_commit));
644 } else {
645 return error(_("%s: Could not drop stash entry"),
646 info->revision.buf);
647 }
648
649 if (reflog_is_empty(ref_stash))
650 do_clear_stash();
651
652 return 0;
653 }
654
655 static void assert_stash_ref(struct stash_info *info)
656 {
657 if (!info->is_stash_ref) {
658 error(_("'%s' is not a stash reference"), info->revision.buf);
659 free_stash_info(info);
660 exit(1);
661 }
662 }
663
664 static int drop_stash(int argc, const char **argv, const char *prefix)
665 {
666 int ret;
667 int quiet = 0;
668 struct stash_info info;
669 struct option options[] = {
670 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
671 OPT_END()
672 };
673
674 argc = parse_options(argc, argv, prefix, options,
675 git_stash_drop_usage, 0);
676
677 if (get_stash_info(&info, argc, argv))
678 return -1;
679
680 assert_stash_ref(&info);
681
682 ret = do_drop_stash(&info, quiet);
683 free_stash_info(&info);
684 return ret;
685 }
686
687 static int pop_stash(int argc, const char **argv, const char *prefix)
688 {
689 int ret;
690 int index = 0;
691 int quiet = 0;
692 struct stash_info info;
693 struct option options[] = {
694 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
695 OPT_BOOL(0, "index", &index,
696 N_("attempt to recreate the index")),
697 OPT_END()
698 };
699
700 argc = parse_options(argc, argv, prefix, options,
701 git_stash_pop_usage, 0);
702
703 if (get_stash_info(&info, argc, argv))
704 return -1;
705
706 assert_stash_ref(&info);
707 if ((ret = do_apply_stash(prefix, &info, index, quiet)))
708 printf_ln(_("The stash entry is kept in case "
709 "you need it again."));
710 else
711 ret = do_drop_stash(&info, quiet);
712
713 free_stash_info(&info);
714 return ret;
715 }
716
717 static int branch_stash(int argc, const char **argv, const char *prefix)
718 {
719 int ret;
720 const char *branch = NULL;
721 struct stash_info info;
722 struct child_process cp = CHILD_PROCESS_INIT;
723 struct option options[] = {
724 OPT_END()
725 };
726
727 argc = parse_options(argc, argv, prefix, options,
728 git_stash_branch_usage, 0);
729
730 if (!argc) {
731 fprintf_ln(stderr, _("No branch name specified"));
732 return -1;
733 }
734
735 branch = argv[0];
736
737 if (get_stash_info(&info, argc - 1, argv + 1))
738 return -1;
739
740 cp.git_cmd = 1;
741 strvec_pushl(&cp.args, "checkout", "-b", NULL);
742 strvec_push(&cp.args, branch);
743 strvec_push(&cp.args, oid_to_hex(&info.b_commit));
744 ret = run_command(&cp);
745 if (!ret)
746 ret = do_apply_stash(prefix, &info, 1, 0);
747 if (!ret && info.is_stash_ref)
748 ret = do_drop_stash(&info, 0);
749
750 free_stash_info(&info);
751
752 return ret;
753 }
754
755 static int list_stash(int argc, const char **argv, const char *prefix)
756 {
757 struct child_process cp = CHILD_PROCESS_INIT;
758 struct option options[] = {
759 OPT_END()
760 };
761
762 argc = parse_options(argc, argv, prefix, options,
763 git_stash_list_usage,
764 PARSE_OPT_KEEP_UNKNOWN);
765
766 if (!ref_exists(ref_stash))
767 return 0;
768
769 cp.git_cmd = 1;
770 strvec_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
771 "--first-parent", NULL);
772 strvec_pushv(&cp.args, argv);
773 strvec_push(&cp.args, ref_stash);
774 strvec_push(&cp.args, "--");
775 return run_command(&cp);
776 }
777
778 static int show_stat = 1;
779 static int show_patch;
780 static int show_include_untracked;
781
782 static int git_stash_config(const char *var, const char *value, void *cb)
783 {
784 if (!strcmp(var, "stash.showstat")) {
785 show_stat = git_config_bool(var, value);
786 return 0;
787 }
788 if (!strcmp(var, "stash.showpatch")) {
789 show_patch = git_config_bool(var, value);
790 return 0;
791 }
792 if (!strcmp(var, "stash.showincludeuntracked")) {
793 show_include_untracked = git_config_bool(var, value);
794 return 0;
795 }
796 return git_diff_basic_config(var, value, cb);
797 }
798
799 static void diff_include_untracked(const struct stash_info *info, struct diff_options *diff_opt)
800 {
801 const struct object_id *oid[] = { &info->w_commit, &info->u_tree };
802 struct tree *tree[ARRAY_SIZE(oid)];
803 struct tree_desc tree_desc[ARRAY_SIZE(oid)];
804 struct unpack_trees_options unpack_tree_opt = { 0 };
805 int i;
806
807 for (i = 0; i < ARRAY_SIZE(oid); i++) {
808 tree[i] = parse_tree_indirect(oid[i]);
809 if (parse_tree(tree[i]) < 0)
810 die(_("failed to parse tree"));
811 init_tree_desc(&tree_desc[i], tree[i]->buffer, tree[i]->size);
812 }
813
814 unpack_tree_opt.head_idx = -1;
815 unpack_tree_opt.src_index = &the_index;
816 unpack_tree_opt.dst_index = &the_index;
817 unpack_tree_opt.merge = 1;
818 unpack_tree_opt.fn = stash_worktree_untracked_merge;
819
820 if (unpack_trees(ARRAY_SIZE(tree_desc), tree_desc, &unpack_tree_opt))
821 die(_("failed to unpack trees"));
822
823 do_diff_cache(&info->b_commit, diff_opt);
824 }
825
826 static int show_stash(int argc, const char **argv, const char *prefix)
827 {
828 int i;
829 int ret = 0;
830 struct stash_info info;
831 struct rev_info rev;
832 struct strvec stash_args = STRVEC_INIT;
833 struct strvec revision_args = STRVEC_INIT;
834 enum {
835 UNTRACKED_NONE,
836 UNTRACKED_INCLUDE,
837 UNTRACKED_ONLY
838 } show_untracked = show_include_untracked ? UNTRACKED_INCLUDE : UNTRACKED_NONE;
839 struct option options[] = {
840 OPT_SET_INT('u', "include-untracked", &show_untracked,
841 N_("include untracked files in the stash"),
842 UNTRACKED_INCLUDE),
843 OPT_SET_INT_F(0, "only-untracked", &show_untracked,
844 N_("only show untracked files in the stash"),
845 UNTRACKED_ONLY, PARSE_OPT_NONEG),
846 OPT_END()
847 };
848
849 init_diff_ui_defaults();
850 git_config(git_diff_ui_config, NULL);
851 init_revisions(&rev, prefix);
852
853 argc = parse_options(argc, argv, prefix, options, git_stash_show_usage,
854 PARSE_OPT_KEEP_ARGV0 | PARSE_OPT_KEEP_UNKNOWN |
855 PARSE_OPT_KEEP_DASHDASH);
856
857 strvec_push(&revision_args, argv[0]);
858 for (i = 1; i < argc; i++) {
859 if (argv[i][0] != '-')
860 strvec_push(&stash_args, argv[i]);
861 else
862 strvec_push(&revision_args, argv[i]);
863 }
864
865 ret = get_stash_info(&info, stash_args.nr, stash_args.v);
866 strvec_clear(&stash_args);
867 if (ret)
868 return -1;
869
870 /*
871 * The config settings are applied only if there are not passed
872 * any options.
873 */
874 if (revision_args.nr == 1) {
875 if (show_stat)
876 rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
877
878 if (show_patch)
879 rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
880
881 if (!show_stat && !show_patch) {
882 free_stash_info(&info);
883 return 0;
884 }
885 }
886
887 argc = setup_revisions(revision_args.nr, revision_args.v, &rev, NULL);
888 if (argc > 1) {
889 free_stash_info(&info);
890 usage_with_options(git_stash_show_usage, options);
891 }
892 if (!rev.diffopt.output_format) {
893 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
894 diff_setup_done(&rev.diffopt);
895 }
896
897 rev.diffopt.flags.recursive = 1;
898 setup_diff_pager(&rev.diffopt);
899 switch (show_untracked) {
900 case UNTRACKED_NONE:
901 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
902 break;
903 case UNTRACKED_ONLY:
904 if (info.has_u)
905 diff_root_tree_oid(&info.u_tree, "", &rev.diffopt);
906 break;
907 case UNTRACKED_INCLUDE:
908 if (info.has_u)
909 diff_include_untracked(&info, &rev.diffopt);
910 else
911 diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
912 break;
913 }
914 log_tree_diff_flush(&rev);
915
916 free_stash_info(&info);
917 return diff_result_code(&rev.diffopt, 0);
918 }
919
920 static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
921 int quiet)
922 {
923 if (!stash_msg)
924 stash_msg = "Created via \"git stash store\".";
925
926 if (update_ref(stash_msg, ref_stash, w_commit, NULL,
927 REF_FORCE_CREATE_REFLOG,
928 quiet ? UPDATE_REFS_QUIET_ON_ERR :
929 UPDATE_REFS_MSG_ON_ERR)) {
930 if (!quiet) {
931 fprintf_ln(stderr, _("Cannot update %s with %s"),
932 ref_stash, oid_to_hex(w_commit));
933 }
934 return -1;
935 }
936
937 return 0;
938 }
939
940 static int store_stash(int argc, const char **argv, const char *prefix)
941 {
942 int quiet = 0;
943 const char *stash_msg = NULL;
944 struct object_id obj;
945 struct object_context dummy;
946 struct option options[] = {
947 OPT__QUIET(&quiet, N_("be quiet")),
948 OPT_STRING('m', "message", &stash_msg, "message",
949 N_("stash message")),
950 OPT_END()
951 };
952
953 argc = parse_options(argc, argv, prefix, options,
954 git_stash_store_usage,
955 PARSE_OPT_KEEP_UNKNOWN);
956
957 if (argc != 1) {
958 if (!quiet)
959 fprintf_ln(stderr, _("\"git stash store\" requires one "
960 "<commit> argument"));
961 return -1;
962 }
963
964 if (get_oid_with_context(the_repository,
965 argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
966 &dummy)) {
967 if (!quiet)
968 fprintf_ln(stderr, _("Cannot update %s with %s"),
969 ref_stash, argv[0]);
970 return -1;
971 }
972
973 return do_store_stash(&obj, stash_msg, quiet);
974 }
975
976 static void add_pathspecs(struct strvec *args,
977 const struct pathspec *ps) {
978 int i;
979
980 for (i = 0; i < ps->nr; i++)
981 strvec_push(args, ps->items[i].original);
982 }
983
984 /*
985 * `untracked_files` will be filled with the names of untracked files.
986 * The return value is:
987 *
988 * = 0 if there are not any untracked files
989 * > 0 if there are untracked files
990 */
991 static int get_untracked_files(const struct pathspec *ps, int include_untracked,
992 struct strbuf *untracked_files)
993 {
994 int i;
995 int found = 0;
996 struct dir_struct dir = DIR_INIT;
997
998 if (include_untracked != INCLUDE_ALL_FILES)
999 setup_standard_excludes(&dir);
1000
1001 fill_directory(&dir, the_repository->index, ps);
1002 for (i = 0; i < dir.nr; i++) {
1003 struct dir_entry *ent = dir.entries[i];
1004 found++;
1005 strbuf_addstr(untracked_files, ent->name);
1006 /* NUL-terminate: will be fed to update-index -z */
1007 strbuf_addch(untracked_files, '\0');
1008 }
1009
1010 dir_clear(&dir);
1011 return found;
1012 }
1013
1014 /*
1015 * The return value of `check_changes_tracked_files()` can be:
1016 *
1017 * < 0 if there was an error
1018 * = 0 if there are no changes.
1019 * > 0 if there are changes.
1020 */
1021 static int check_changes_tracked_files(const struct pathspec *ps)
1022 {
1023 int result;
1024 struct rev_info rev;
1025 struct object_id dummy;
1026 int ret = 0;
1027
1028 /* No initial commit. */
1029 if (get_oid("HEAD", &dummy))
1030 return -1;
1031
1032 if (read_cache() < 0)
1033 return -1;
1034
1035 init_revisions(&rev, NULL);
1036 copy_pathspec(&rev.prune_data, ps);
1037
1038 rev.diffopt.flags.quick = 1;
1039 rev.diffopt.flags.ignore_submodules = 1;
1040 rev.abbrev = 0;
1041
1042 add_head_to_pending(&rev);
1043 diff_setup_done(&rev.diffopt);
1044
1045 result = run_diff_index(&rev, 1);
1046 if (diff_result_code(&rev.diffopt, result)) {
1047 ret = 1;
1048 goto done;
1049 }
1050
1051 object_array_clear(&rev.pending);
1052 result = run_diff_files(&rev, 0);
1053 if (diff_result_code(&rev.diffopt, result)) {
1054 ret = 1;
1055 goto done;
1056 }
1057
1058 done:
1059 clear_pathspec(&rev.prune_data);
1060 return ret;
1061 }
1062
1063 /*
1064 * The function will fill `untracked_files` with the names of untracked files
1065 * It will return 1 if there were any changes and 0 if there were not.
1066 */
1067 static int check_changes(const struct pathspec *ps, int include_untracked,
1068 struct strbuf *untracked_files)
1069 {
1070 int ret = 0;
1071 if (check_changes_tracked_files(ps))
1072 ret = 1;
1073
1074 if (include_untracked && get_untracked_files(ps, include_untracked,
1075 untracked_files))
1076 ret = 1;
1077
1078 return ret;
1079 }
1080
1081 static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
1082 struct strbuf files)
1083 {
1084 int ret = 0;
1085 struct strbuf untracked_msg = STRBUF_INIT;
1086 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1087 struct index_state istate = { NULL };
1088
1089 cp_upd_index.git_cmd = 1;
1090 strvec_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
1091 "--remove", "--stdin", NULL);
1092 strvec_pushf(&cp_upd_index.env_array, "GIT_INDEX_FILE=%s",
1093 stash_index_path.buf);
1094
1095 strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
1096 if (pipe_command(&cp_upd_index, files.buf, files.len, NULL, 0,
1097 NULL, 0)) {
1098 ret = -1;
1099 goto done;
1100 }
1101
1102 if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
1103 NULL)) {
1104 ret = -1;
1105 goto done;
1106 }
1107
1108 if (commit_tree(untracked_msg.buf, untracked_msg.len,
1109 &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
1110 ret = -1;
1111 goto done;
1112 }
1113
1114 done:
1115 discard_index(&istate);
1116 strbuf_release(&untracked_msg);
1117 remove_path(stash_index_path.buf);
1118 return ret;
1119 }
1120
1121 static int stash_staged(struct stash_info *info, struct strbuf *out_patch,
1122 int quiet)
1123 {
1124 int ret = 0;
1125 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1126 struct index_state istate = { NULL };
1127
1128 if (write_index_as_tree(&info->w_tree, &istate, the_repository->index_file,
1129 0, NULL)) {
1130 ret = -1;
1131 goto done;
1132 }
1133
1134 cp_diff_tree.git_cmd = 1;
1135 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1136 oid_to_hex(&info->w_tree), "--", NULL);
1137 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1138 ret = -1;
1139 goto done;
1140 }
1141
1142 if (!out_patch->len) {
1143 if (!quiet)
1144 fprintf_ln(stderr, _("No staged changes"));
1145 ret = 1;
1146 }
1147
1148 done:
1149 discard_index(&istate);
1150 return ret;
1151 }
1152
1153 static int stash_patch(struct stash_info *info, const struct pathspec *ps,
1154 struct strbuf *out_patch, int quiet)
1155 {
1156 int ret = 0;
1157 struct child_process cp_read_tree = CHILD_PROCESS_INIT;
1158 struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1159 struct index_state istate = { NULL };
1160 char *old_index_env = NULL, *old_repo_index_file;
1161
1162 remove_path(stash_index_path.buf);
1163
1164 cp_read_tree.git_cmd = 1;
1165 strvec_pushl(&cp_read_tree.args, "read-tree", "HEAD", NULL);
1166 strvec_pushf(&cp_read_tree.env_array, "GIT_INDEX_FILE=%s",
1167 stash_index_path.buf);
1168 if (run_command(&cp_read_tree)) {
1169 ret = -1;
1170 goto done;
1171 }
1172
1173 /* Find out what the user wants. */
1174 old_repo_index_file = the_repository->index_file;
1175 the_repository->index_file = stash_index_path.buf;
1176 old_index_env = xstrdup_or_null(getenv(INDEX_ENVIRONMENT));
1177 setenv(INDEX_ENVIRONMENT, the_repository->index_file, 1);
1178
1179 ret = run_add_interactive(NULL, "--patch=stash", ps);
1180
1181 the_repository->index_file = old_repo_index_file;
1182 if (old_index_env && *old_index_env)
1183 setenv(INDEX_ENVIRONMENT, old_index_env, 1);
1184 else
1185 unsetenv(INDEX_ENVIRONMENT);
1186 FREE_AND_NULL(old_index_env);
1187
1188 /* State of the working tree. */
1189 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1190 NULL)) {
1191 ret = -1;
1192 goto done;
1193 }
1194
1195 cp_diff_tree.git_cmd = 1;
1196 strvec_pushl(&cp_diff_tree.args, "diff-tree", "-p", "-U1", "HEAD",
1197 oid_to_hex(&info->w_tree), "--", NULL);
1198 if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1199 ret = -1;
1200 goto done;
1201 }
1202
1203 if (!out_patch->len) {
1204 if (!quiet)
1205 fprintf_ln(stderr, _("No changes selected"));
1206 ret = 1;
1207 }
1208
1209 done:
1210 discard_index(&istate);
1211 remove_path(stash_index_path.buf);
1212 return ret;
1213 }
1214
1215 static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
1216 {
1217 int ret = 0;
1218 struct rev_info rev;
1219 struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1220 struct strbuf diff_output = STRBUF_INIT;
1221 struct index_state istate = { NULL };
1222
1223 init_revisions(&rev, NULL);
1224 copy_pathspec(&rev.prune_data, ps);
1225
1226 set_alternate_index_output(stash_index_path.buf);
1227 if (reset_tree(&info->i_tree, 0, 0)) {
1228 ret = -1;
1229 goto done;
1230 }
1231 set_alternate_index_output(NULL);
1232
1233 rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1234 rev.diffopt.format_callback = add_diff_to_buf;
1235 rev.diffopt.format_callback_data = &diff_output;
1236
1237 if (read_cache_preload(&rev.diffopt.pathspec) < 0) {
1238 ret = -1;
1239 goto done;
1240 }
1241
1242 add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1243 "");
1244 if (run_diff_index(&rev, 0)) {
1245 ret = -1;
1246 goto done;
1247 }
1248
1249 cp_upd_index.git_cmd = 1;
1250 strvec_pushl(&cp_upd_index.args, "update-index",
1251 "--ignore-skip-worktree-entries",
1252 "-z", "--add", "--remove", "--stdin", NULL);
1253 strvec_pushf(&cp_upd_index.env_array, "GIT_INDEX_FILE=%s",
1254 stash_index_path.buf);
1255
1256 if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1257 NULL, 0, NULL, 0)) {
1258 ret = -1;
1259 goto done;
1260 }
1261
1262 if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1263 NULL)) {
1264 ret = -1;
1265 goto done;
1266 }
1267
1268 done:
1269 discard_index(&istate);
1270 UNLEAK(rev);
1271 object_array_clear(&rev.pending);
1272 clear_pathspec(&rev.prune_data);
1273 strbuf_release(&diff_output);
1274 remove_path(stash_index_path.buf);
1275 return ret;
1276 }
1277
1278 static int do_create_stash(const struct pathspec *ps, struct strbuf *stash_msg_buf,
1279 int include_untracked, int patch_mode, int only_staged,
1280 struct stash_info *info, struct strbuf *patch,
1281 int quiet)
1282 {
1283 int ret = 0;
1284 int flags = 0;
1285 int untracked_commit_option = 0;
1286 const char *head_short_sha1 = NULL;
1287 const char *branch_ref = NULL;
1288 const char *branch_name = "(no branch)";
1289 struct commit *head_commit = NULL;
1290 struct commit_list *parents = NULL;
1291 struct strbuf msg = STRBUF_INIT;
1292 struct strbuf commit_tree_label = STRBUF_INIT;
1293 struct strbuf untracked_files = STRBUF_INIT;
1294
1295 prepare_fallback_ident("git stash", "git@stash");
1296
1297 read_cache_preload(NULL);
1298 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0) < 0) {
1299 ret = -1;
1300 goto done;
1301 }
1302
1303 if (get_oid("HEAD", &info->b_commit)) {
1304 if (!quiet)
1305 fprintf_ln(stderr, _("You do not have "
1306 "the initial commit yet"));
1307 ret = -1;
1308 goto done;
1309 } else {
1310 head_commit = lookup_commit(the_repository, &info->b_commit);
1311 }
1312
1313 if (!check_changes(ps, include_untracked, &untracked_files)) {
1314 ret = 1;
1315 goto done;
1316 }
1317
1318 branch_ref = resolve_ref_unsafe("HEAD", 0, NULL, &flags);
1319 if (flags & REF_ISSYMREF)
1320 skip_prefix(branch_ref, "refs/heads/", &branch_name);
1321 head_short_sha1 = find_unique_abbrev(&head_commit->object.oid,
1322 DEFAULT_ABBREV);
1323 strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1324 pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1325
1326 strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1327 commit_list_insert(head_commit, &parents);
1328 if (write_cache_as_tree(&info->i_tree, 0, NULL) ||
1329 commit_tree(commit_tree_label.buf, commit_tree_label.len,
1330 &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1331 if (!quiet)
1332 fprintf_ln(stderr, _("Cannot save the current "
1333 "index state"));
1334 ret = -1;
1335 goto done;
1336 }
1337
1338 if (include_untracked) {
1339 if (save_untracked_files(info, &msg, untracked_files)) {
1340 if (!quiet)
1341 fprintf_ln(stderr, _("Cannot save "
1342 "the untracked files"));
1343 ret = -1;
1344 goto done;
1345 }
1346 untracked_commit_option = 1;
1347 }
1348 if (patch_mode) {
1349 ret = stash_patch(info, ps, patch, quiet);
1350 if (ret < 0) {
1351 if (!quiet)
1352 fprintf_ln(stderr, _("Cannot save the current "
1353 "worktree state"));
1354 goto done;
1355 } else if (ret > 0) {
1356 goto done;
1357 }
1358 } else if (only_staged) {
1359 ret = stash_staged(info, patch, quiet);
1360 if (ret < 0) {
1361 if (!quiet)
1362 fprintf_ln(stderr, _("Cannot save the current "
1363 "staged state"));
1364 goto done;
1365 } else if (ret > 0) {
1366 goto done;
1367 }
1368 } else {
1369 if (stash_working_tree(info, ps)) {
1370 if (!quiet)
1371 fprintf_ln(stderr, _("Cannot save the current "
1372 "worktree state"));
1373 ret = -1;
1374 goto done;
1375 }
1376 }
1377
1378 if (!stash_msg_buf->len)
1379 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1380 else
1381 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1382
1383 /*
1384 * `parents` will be empty after calling `commit_tree()`, so there is
1385 * no need to call `free_commit_list()`
1386 */
1387 parents = NULL;
1388 if (untracked_commit_option)
1389 commit_list_insert(lookup_commit(the_repository,
1390 &info->u_commit),
1391 &parents);
1392 commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1393 &parents);
1394 commit_list_insert(head_commit, &parents);
1395
1396 if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1397 parents, &info->w_commit, NULL, NULL)) {
1398 if (!quiet)
1399 fprintf_ln(stderr, _("Cannot record "
1400 "working tree state"));
1401 ret = -1;
1402 goto done;
1403 }
1404
1405 done:
1406 strbuf_release(&commit_tree_label);
1407 strbuf_release(&msg);
1408 strbuf_release(&untracked_files);
1409 return ret;
1410 }
1411
1412 static int create_stash(int argc, const char **argv, const char *prefix)
1413 {
1414 int ret = 0;
1415 struct strbuf stash_msg_buf = STRBUF_INIT;
1416 struct stash_info info;
1417 struct pathspec ps;
1418
1419 /* Starting with argv[1], since argv[0] is "create" */
1420 strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
1421
1422 memset(&ps, 0, sizeof(ps));
1423 if (!check_changes_tracked_files(&ps))
1424 return 0;
1425
1426 ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, 0, &info,
1427 NULL, 0);
1428 if (!ret)
1429 printf_ln("%s", oid_to_hex(&info.w_commit));
1430
1431 strbuf_release(&stash_msg_buf);
1432 return ret;
1433 }
1434
1435 static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int quiet,
1436 int keep_index, int patch_mode, int include_untracked, int only_staged)
1437 {
1438 int ret = 0;
1439 struct stash_info info;
1440 struct strbuf patch = STRBUF_INIT;
1441 struct strbuf stash_msg_buf = STRBUF_INIT;
1442 struct strbuf untracked_files = STRBUF_INIT;
1443
1444 if (patch_mode && keep_index == -1)
1445 keep_index = 1;
1446
1447 if (patch_mode && include_untracked) {
1448 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1449 " or --all at the same time"));
1450 ret = -1;
1451 goto done;
1452 }
1453
1454 /* --patch overrides --staged */
1455 if (patch_mode)
1456 only_staged = 0;
1457
1458 if (only_staged && include_untracked) {
1459 fprintf_ln(stderr, _("Can't use --staged and --include-untracked"
1460 " or --all at the same time"));
1461 ret = -1;
1462 goto done;
1463 }
1464
1465 read_cache_preload(NULL);
1466 if (!include_untracked && ps->nr) {
1467 int i;
1468 char *ps_matched = xcalloc(ps->nr, 1);
1469
1470 /* TODO: audit for interaction with sparse-index. */
1471 ensure_full_index(&the_index);
1472 for (i = 0; i < active_nr; i++)
1473 ce_path_match(&the_index, active_cache[i], ps,
1474 ps_matched);
1475
1476 if (report_path_error(ps_matched, ps)) {
1477 fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1478 ret = -1;
1479 free(ps_matched);
1480 goto done;
1481 }
1482 free(ps_matched);
1483 }
1484
1485 if (refresh_and_write_cache(REFRESH_QUIET, 0, 0)) {
1486 ret = -1;
1487 goto done;
1488 }
1489
1490 if (!check_changes(ps, include_untracked, &untracked_files)) {
1491 if (!quiet)
1492 printf_ln(_("No local changes to save"));
1493 goto done;
1494 }
1495
1496 if (!reflog_exists(ref_stash) && do_clear_stash()) {
1497 ret = -1;
1498 if (!quiet)
1499 fprintf_ln(stderr, _("Cannot initialize stash"));
1500 goto done;
1501 }
1502
1503 if (stash_msg)
1504 strbuf_addstr(&stash_msg_buf, stash_msg);
1505 if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode, only_staged,
1506 &info, &patch, quiet)) {
1507 ret = -1;
1508 goto done;
1509 }
1510
1511 if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1512 ret = -1;
1513 if (!quiet)
1514 fprintf_ln(stderr, _("Cannot save the current status"));
1515 goto done;
1516 }
1517
1518 if (!quiet)
1519 printf_ln(_("Saved working directory and index state %s"),
1520 stash_msg_buf.buf);
1521
1522 if (!(patch_mode || only_staged)) {
1523 if (include_untracked && !ps->nr) {
1524 struct child_process cp = CHILD_PROCESS_INIT;
1525
1526 cp.git_cmd = 1;
1527 if (startup_info->original_cwd) {
1528 cp.dir = startup_info->original_cwd;
1529 strvec_pushf(&cp.env_array, "%s=%s",
1530 GIT_WORK_TREE_ENVIRONMENT,
1531 the_repository->worktree);
1532 }
1533 strvec_pushl(&cp.args, "clean", "--force",
1534 "--quiet", "-d", ":/", NULL);
1535 if (include_untracked == INCLUDE_ALL_FILES)
1536 strvec_push(&cp.args, "-x");
1537 if (run_command(&cp)) {
1538 ret = -1;
1539 goto done;
1540 }
1541 }
1542 discard_cache();
1543 if (ps->nr) {
1544 struct child_process cp_add = CHILD_PROCESS_INIT;
1545 struct child_process cp_diff = CHILD_PROCESS_INIT;
1546 struct child_process cp_apply = CHILD_PROCESS_INIT;
1547 struct strbuf out = STRBUF_INIT;
1548
1549 cp_add.git_cmd = 1;
1550 strvec_push(&cp_add.args, "add");
1551 if (!include_untracked)
1552 strvec_push(&cp_add.args, "-u");
1553 if (include_untracked == INCLUDE_ALL_FILES)
1554 strvec_push(&cp_add.args, "--force");
1555 strvec_push(&cp_add.args, "--");
1556 add_pathspecs(&cp_add.args, ps);
1557 if (run_command(&cp_add)) {
1558 ret = -1;
1559 goto done;
1560 }
1561
1562 cp_diff.git_cmd = 1;
1563 strvec_pushl(&cp_diff.args, "diff-index", "-p",
1564 "--cached", "--binary", "HEAD", "--",
1565 NULL);
1566 add_pathspecs(&cp_diff.args, ps);
1567 if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1568 ret = -1;
1569 goto done;
1570 }
1571
1572 cp_apply.git_cmd = 1;
1573 strvec_pushl(&cp_apply.args, "apply", "--index",
1574 "-R", NULL);
1575 if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1576 NULL, 0)) {
1577 ret = -1;
1578 goto done;
1579 }
1580 } else {
1581 struct child_process cp = CHILD_PROCESS_INIT;
1582 cp.git_cmd = 1;
1583 /* BUG: this nukes untracked files in the way */
1584 strvec_pushl(&cp.args, "reset", "--hard", "-q",
1585 "--no-recurse-submodules", NULL);
1586 if (run_command(&cp)) {
1587 ret = -1;
1588 goto done;
1589 }
1590 }
1591
1592 if (keep_index == 1 && !is_null_oid(&info.i_tree)) {
1593 struct child_process cp = CHILD_PROCESS_INIT;
1594
1595 cp.git_cmd = 1;
1596 strvec_pushl(&cp.args, "checkout", "--no-overlay",
1597 oid_to_hex(&info.i_tree), "--", NULL);
1598 if (!ps->nr)
1599 strvec_push(&cp.args, ":/");
1600 else
1601 add_pathspecs(&cp.args, ps);
1602 if (run_command(&cp)) {
1603 ret = -1;
1604 goto done;
1605 }
1606 }
1607 goto done;
1608 } else {
1609 struct child_process cp = CHILD_PROCESS_INIT;
1610
1611 cp.git_cmd = 1;
1612 strvec_pushl(&cp.args, "apply", "-R", NULL);
1613
1614 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1615 if (!quiet)
1616 fprintf_ln(stderr, _("Cannot remove "
1617 "worktree changes"));
1618 ret = -1;
1619 goto done;
1620 }
1621
1622 if (keep_index < 1) {
1623 struct child_process cp = CHILD_PROCESS_INIT;
1624
1625 cp.git_cmd = 1;
1626 strvec_pushl(&cp.args, "reset", "-q", "--", NULL);
1627 add_pathspecs(&cp.args, ps);
1628 if (run_command(&cp)) {
1629 ret = -1;
1630 goto done;
1631 }
1632 }
1633 goto done;
1634 }
1635
1636 done:
1637 strbuf_release(&stash_msg_buf);
1638 return ret;
1639 }
1640
1641 static int push_stash(int argc, const char **argv, const char *prefix,
1642 int push_assumed)
1643 {
1644 int force_assume = 0;
1645 int keep_index = -1;
1646 int only_staged = 0;
1647 int patch_mode = 0;
1648 int include_untracked = 0;
1649 int quiet = 0;
1650 int pathspec_file_nul = 0;
1651 const char *stash_msg = NULL;
1652 const char *pathspec_from_file = NULL;
1653 struct pathspec ps;
1654 struct option options[] = {
1655 OPT_BOOL('k', "keep-index", &keep_index,
1656 N_("keep index")),
1657 OPT_BOOL('S', "staged", &only_staged,
1658 N_("stash staged changes only")),
1659 OPT_BOOL('p', "patch", &patch_mode,
1660 N_("stash in patch mode")),
1661 OPT__QUIET(&quiet, N_("quiet mode")),
1662 OPT_BOOL('u', "include-untracked", &include_untracked,
1663 N_("include untracked files in stash")),
1664 OPT_SET_INT('a', "all", &include_untracked,
1665 N_("include ignore files"), 2),
1666 OPT_STRING('m', "message", &stash_msg, N_("message"),
1667 N_("stash message")),
1668 OPT_PATHSPEC_FROM_FILE(&pathspec_from_file),
1669 OPT_PATHSPEC_FILE_NUL(&pathspec_file_nul),
1670 OPT_END()
1671 };
1672
1673 if (argc) {
1674 force_assume = !strcmp(argv[0], "-p");
1675 argc = parse_options(argc, argv, prefix, options,
1676 push_assumed ? git_stash_usage :
1677 git_stash_push_usage,
1678 PARSE_OPT_KEEP_DASHDASH);
1679 }
1680
1681 if (argc) {
1682 if (!strcmp(argv[0], "--")) {
1683 argc--;
1684 argv++;
1685 } else if (push_assumed && !force_assume) {
1686 die("subcommand wasn't specified; 'push' can't be assumed due to unexpected token '%s'",
1687 argv[0]);
1688 }
1689 }
1690
1691 parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1692 prefix, argv);
1693
1694 if (pathspec_from_file) {
1695 if (patch_mode)
1696 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--patch");
1697
1698 if (only_staged)
1699 die(_("options '%s' and '%s' cannot be used together"), "--pathspec-from-file", "--staged");
1700
1701 if (ps.nr)
1702 die(_("'%s' and pathspec arguments cannot be used together"), "--pathspec-from-file");
1703
1704 parse_pathspec_file(&ps, 0,
1705 PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1706 prefix, pathspec_from_file, pathspec_file_nul);
1707 } else if (pathspec_file_nul) {
1708 die(_("the option '%s' requires '%s'"), "--pathspec-file-nul", "--pathspec-from-file");
1709 }
1710
1711 return do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
1712 include_untracked, only_staged);
1713 }
1714
1715 static int save_stash(int argc, const char **argv, const char *prefix)
1716 {
1717 int keep_index = -1;
1718 int only_staged = 0;
1719 int patch_mode = 0;
1720 int include_untracked = 0;
1721 int quiet = 0;
1722 int ret = 0;
1723 const char *stash_msg = NULL;
1724 struct pathspec ps;
1725 struct strbuf stash_msg_buf = STRBUF_INIT;
1726 struct option options[] = {
1727 OPT_BOOL('k', "keep-index", &keep_index,
1728 N_("keep index")),
1729 OPT_BOOL('S', "staged", &only_staged,
1730 N_("stash staged changes only")),
1731 OPT_BOOL('p', "patch", &patch_mode,
1732 N_("stash in patch mode")),
1733 OPT__QUIET(&quiet, N_("quiet mode")),
1734 OPT_BOOL('u', "include-untracked", &include_untracked,
1735 N_("include untracked files in stash")),
1736 OPT_SET_INT('a', "all", &include_untracked,
1737 N_("include ignore files"), 2),
1738 OPT_STRING('m', "message", &stash_msg, "message",
1739 N_("stash message")),
1740 OPT_END()
1741 };
1742
1743 argc = parse_options(argc, argv, prefix, options,
1744 git_stash_save_usage,
1745 PARSE_OPT_KEEP_DASHDASH);
1746
1747 if (argc)
1748 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
1749
1750 memset(&ps, 0, sizeof(ps));
1751 ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
1752 patch_mode, include_untracked, only_staged);
1753
1754 strbuf_release(&stash_msg_buf);
1755 return ret;
1756 }
1757
1758 int cmd_stash(int argc, const char **argv, const char *prefix)
1759 {
1760 pid_t pid = getpid();
1761 const char *index_file;
1762 struct strvec args = STRVEC_INIT;
1763
1764 struct option options[] = {
1765 OPT_END()
1766 };
1767
1768 git_config(git_stash_config, NULL);
1769
1770 argc = parse_options(argc, argv, prefix, options, git_stash_usage,
1771 PARSE_OPT_KEEP_UNKNOWN | PARSE_OPT_KEEP_DASHDASH);
1772
1773 index_file = get_index_file();
1774 strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
1775 (uintmax_t)pid);
1776
1777 if (!argc)
1778 return !!push_stash(0, NULL, prefix, 0);
1779 else if (!strcmp(argv[0], "apply"))
1780 return !!apply_stash(argc, argv, prefix);
1781 else if (!strcmp(argv[0], "clear"))
1782 return !!clear_stash(argc, argv, prefix);
1783 else if (!strcmp(argv[0], "drop"))
1784 return !!drop_stash(argc, argv, prefix);
1785 else if (!strcmp(argv[0], "pop"))
1786 return !!pop_stash(argc, argv, prefix);
1787 else if (!strcmp(argv[0], "branch"))
1788 return !!branch_stash(argc, argv, prefix);
1789 else if (!strcmp(argv[0], "list"))
1790 return !!list_stash(argc, argv, prefix);
1791 else if (!strcmp(argv[0], "show"))
1792 return !!show_stash(argc, argv, prefix);
1793 else if (!strcmp(argv[0], "store"))
1794 return !!store_stash(argc, argv, prefix);
1795 else if (!strcmp(argv[0], "create"))
1796 return !!create_stash(argc, argv, prefix);
1797 else if (!strcmp(argv[0], "push"))
1798 return !!push_stash(argc, argv, prefix, 0);
1799 else if (!strcmp(argv[0], "save"))
1800 return !!save_stash(argc, argv, prefix);
1801 else if (*argv[0] != '-')
1802 usage_msg_optf(_("unknown subcommand: %s"),
1803 git_stash_usage, options, argv[0]);
1804
1805 /* Assume 'stash push' */
1806 strvec_push(&args, "push");
1807 strvec_pushv(&args, argv);
1808 return !!push_stash(args.nr, args.v, prefix, 1);
1809 }