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