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