Merge branch 'jk/no-flush-upon-disconnecting-slrpc-transport' into maint
[git] / builtin / stash.c
1 #define USE_THE_INDEX_COMPATIBILITY_MACROS
2 #include "builtin.h"
3 #include "config.h"
4 #include "parse-options.h"
5 #include "refs.h"
6 #include "lockfile.h"
7 #include "cache-tree.h"
8 #include "unpack-trees.h"
9 #include "merge-recursive.h"
10 #include "argv-array.h"
11 #include "run-command.h"
12 #include "dir.h"
13 #include "rerere.h"
14 #include "revision.h"
15 #include "log-tree.h"
16 #include "diffcore.h"
17 #include "exec-cmd.h"
18
19 #define INCLUDE_ALL_FILES 2
20
21 static 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"
29            "          [-u|--include-untracked] [-a|--all] [-m|--message <message>]\n"
30            "          [--] [<pathspec>...]]"),
31         N_("git stash save [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
32            "          [-u|--include-untracked] [-a|--all] [<message>]"),
33         NULL
34 };
35
36 static const char * const git_stash_list_usage[] = {
37         N_("git stash list [<options>]"),
38         NULL
39 };
40
41 static const char * const git_stash_show_usage[] = {
42         N_("git stash show [<options>] [<stash>]"),
43         NULL
44 };
45
46 static const char * const git_stash_drop_usage[] = {
47         N_("git stash drop [-q|--quiet] [<stash>]"),
48         NULL
49 };
50
51 static const char * const git_stash_pop_usage[] = {
52         N_("git stash pop [--index] [-q|--quiet] [<stash>]"),
53         NULL
54 };
55
56 static const char * const git_stash_apply_usage[] = {
57         N_("git stash apply [--index] [-q|--quiet] [<stash>]"),
58         NULL
59 };
60
61 static const char * const git_stash_branch_usage[] = {
62         N_("git stash branch <branchname> [<stash>]"),
63         NULL
64 };
65
66 static const char * const git_stash_clear_usage[] = {
67         N_("git stash clear"),
68         NULL
69 };
70
71 static const char * const git_stash_store_usage[] = {
72         N_("git stash store [-m|--message <message>] [-q|--quiet] <commit>"),
73         NULL
74 };
75
76 static const char * const git_stash_push_usage[] = {
77         N_("git stash [push [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
78            "          [-u|--include-untracked] [-a|--all] [-m|--message <message>]\n"
79            "          [--] [<pathspec>...]]"),
80         NULL
81 };
82
83 static const char * const git_stash_save_usage[] = {
84         N_("git stash save [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
85            "          [-u|--include-untracked] [-a|--all] [<message>]"),
86         NULL
87 };
88
89 static const char *ref_stash = "refs/stash";
90 static 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  */
102 struct 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
116 static void free_stash_info(struct stash_info *info)
117 {
118         strbuf_release(&info->revision);
119 }
120
121 static 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
130 static 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
204 static 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
213 static 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,
220                              git_stash_clear_usage,
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
230 static 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
269 static 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
285 static 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
299 static 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
313 static 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
327 static 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
343 static 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
356 static 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
387 static 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);
399         if (refresh_and_write_cache(REFRESH_QUIET, 0, 0))
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                         discard_cache();
431                         read_cache();
432                 }
433         }
434
435         if (info->has_u && restore_untracked(&info->u_tree))
436                 return error(_("could not restore untracked files from stash"));
437
438         init_merge_options(&o, the_repository);
439
440         o.branch1 = "Updated upstream";
441         o.branch2 = "Stashed changes";
442
443         if (oideq(&info->b_tree, &c_tree))
444                 o.branch1 = "Version stash was based on";
445
446         if (quiet)
447                 o.verbosity = 0;
448
449         if (o.verbosity >= 3)
450                 printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
451
452         bases[0] = &info->b_tree;
453
454         ret = merge_recursive_generic(&o, &c_tree, &info->w_tree, 1, bases,
455                                       &result);
456         if (ret) {
457                 rerere(0);
458
459                 if (index)
460                         fprintf_ln(stderr, _("Index was not unstashed."));
461
462                 return ret;
463         }
464
465         if (has_index) {
466                 if (reset_tree(&index_tree, 0, 0))
467                         return -1;
468         } else {
469                 struct strbuf out = STRBUF_INIT;
470
471                 if (get_newly_staged(&out, &c_tree)) {
472                         strbuf_release(&out);
473                         return -1;
474                 }
475
476                 if (reset_tree(&c_tree, 0, 1)) {
477                         strbuf_release(&out);
478                         return -1;
479                 }
480
481                 ret = update_index(&out);
482                 strbuf_release(&out);
483                 if (ret)
484                         return -1;
485
486                 /* read back the result of update_index() back from the disk */
487                 discard_cache();
488                 read_cache();
489         }
490
491         if (!quiet) {
492                 struct child_process cp = CHILD_PROCESS_INIT;
493
494                 /*
495                  * Status is quite simple and could be replaced with calls to
496                  * wt_status in the future, but it adds complexities which may
497                  * require more tests.
498                  */
499                 cp.git_cmd = 1;
500                 cp.dir = prefix;
501                 argv_array_pushf(&cp.env_array, GIT_WORK_TREE_ENVIRONMENT"=%s",
502                                  absolute_path(get_git_work_tree()));
503                 argv_array_pushf(&cp.env_array, GIT_DIR_ENVIRONMENT"=%s",
504                                  absolute_path(get_git_dir()));
505                 argv_array_push(&cp.args, "status");
506                 run_command(&cp);
507         }
508
509         return 0;
510 }
511
512 static int apply_stash(int argc, const char **argv, const char *prefix)
513 {
514         int ret;
515         int quiet = 0;
516         int index = 0;
517         struct stash_info info;
518         struct option options[] = {
519                 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
520                 OPT_BOOL(0, "index", &index,
521                          N_("attempt to recreate the index")),
522                 OPT_END()
523         };
524
525         argc = parse_options(argc, argv, prefix, options,
526                              git_stash_apply_usage, 0);
527
528         if (get_stash_info(&info, argc, argv))
529                 return -1;
530
531         ret = do_apply_stash(prefix, &info, index, quiet);
532         free_stash_info(&info);
533         return ret;
534 }
535
536 static int do_drop_stash(struct stash_info *info, int quiet)
537 {
538         int ret;
539         struct child_process cp_reflog = CHILD_PROCESS_INIT;
540         struct child_process cp = CHILD_PROCESS_INIT;
541
542         /*
543          * reflog does not provide a simple function for deleting refs. One will
544          * need to be added to avoid implementing too much reflog code here
545          */
546
547         cp_reflog.git_cmd = 1;
548         argv_array_pushl(&cp_reflog.args, "reflog", "delete", "--updateref",
549                          "--rewrite", NULL);
550         argv_array_push(&cp_reflog.args, info->revision.buf);
551         ret = run_command(&cp_reflog);
552         if (!ret) {
553                 if (!quiet)
554                         printf_ln(_("Dropped %s (%s)"), info->revision.buf,
555                                   oid_to_hex(&info->w_commit));
556         } else {
557                 return error(_("%s: Could not drop stash entry"),
558                              info->revision.buf);
559         }
560
561         /*
562          * This could easily be replaced by get_oid, but currently it will throw
563          * a fatal error when a reflog is empty, which we can not recover from.
564          */
565         cp.git_cmd = 1;
566         /* Even though --quiet is specified, rev-parse still outputs the hash */
567         cp.no_stdout = 1;
568         argv_array_pushl(&cp.args, "rev-parse", "--verify", "--quiet", NULL);
569         argv_array_pushf(&cp.args, "%s@{0}", ref_stash);
570         ret = run_command(&cp);
571
572         /* do_clear_stash if we just dropped the last stash entry */
573         if (ret)
574                 do_clear_stash();
575
576         return 0;
577 }
578
579 static void assert_stash_ref(struct stash_info *info)
580 {
581         if (!info->is_stash_ref) {
582                 error(_("'%s' is not a stash reference"), info->revision.buf);
583                 free_stash_info(info);
584                 exit(1);
585         }
586 }
587
588 static int drop_stash(int argc, const char **argv, const char *prefix)
589 {
590         int ret;
591         int quiet = 0;
592         struct stash_info info;
593         struct option options[] = {
594                 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
595                 OPT_END()
596         };
597
598         argc = parse_options(argc, argv, prefix, options,
599                              git_stash_drop_usage, 0);
600
601         if (get_stash_info(&info, argc, argv))
602                 return -1;
603
604         assert_stash_ref(&info);
605
606         ret = do_drop_stash(&info, quiet);
607         free_stash_info(&info);
608         return ret;
609 }
610
611 static int pop_stash(int argc, const char **argv, const char *prefix)
612 {
613         int ret;
614         int index = 0;
615         int quiet = 0;
616         struct stash_info info;
617         struct option options[] = {
618                 OPT__QUIET(&quiet, N_("be quiet, only report errors")),
619                 OPT_BOOL(0, "index", &index,
620                          N_("attempt to recreate the index")),
621                 OPT_END()
622         };
623
624         argc = parse_options(argc, argv, prefix, options,
625                              git_stash_pop_usage, 0);
626
627         if (get_stash_info(&info, argc, argv))
628                 return -1;
629
630         assert_stash_ref(&info);
631         if ((ret = do_apply_stash(prefix, &info, index, quiet)))
632                 printf_ln(_("The stash entry is kept in case "
633                             "you need it again."));
634         else
635                 ret = do_drop_stash(&info, quiet);
636
637         free_stash_info(&info);
638         return ret;
639 }
640
641 static int branch_stash(int argc, const char **argv, const char *prefix)
642 {
643         int ret;
644         const char *branch = NULL;
645         struct stash_info info;
646         struct child_process cp = CHILD_PROCESS_INIT;
647         struct option options[] = {
648                 OPT_END()
649         };
650
651         argc = parse_options(argc, argv, prefix, options,
652                              git_stash_branch_usage, 0);
653
654         if (!argc) {
655                 fprintf_ln(stderr, _("No branch name specified"));
656                 return -1;
657         }
658
659         branch = argv[0];
660
661         if (get_stash_info(&info, argc - 1, argv + 1))
662                 return -1;
663
664         cp.git_cmd = 1;
665         argv_array_pushl(&cp.args, "checkout", "-b", NULL);
666         argv_array_push(&cp.args, branch);
667         argv_array_push(&cp.args, oid_to_hex(&info.b_commit));
668         ret = run_command(&cp);
669         if (!ret)
670                 ret = do_apply_stash(prefix, &info, 1, 0);
671         if (!ret && info.is_stash_ref)
672                 ret = do_drop_stash(&info, 0);
673
674         free_stash_info(&info);
675
676         return ret;
677 }
678
679 static int list_stash(int argc, const char **argv, const char *prefix)
680 {
681         struct child_process cp = CHILD_PROCESS_INIT;
682         struct option options[] = {
683                 OPT_END()
684         };
685
686         argc = parse_options(argc, argv, prefix, options,
687                              git_stash_list_usage,
688                              PARSE_OPT_KEEP_UNKNOWN);
689
690         if (!ref_exists(ref_stash))
691                 return 0;
692
693         cp.git_cmd = 1;
694         argv_array_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
695                          "--first-parent", "-m", NULL);
696         argv_array_pushv(&cp.args, argv);
697         argv_array_push(&cp.args, ref_stash);
698         argv_array_push(&cp.args, "--");
699         return run_command(&cp);
700 }
701
702 static int show_stat = 1;
703 static int show_patch;
704
705 static int git_stash_config(const char *var, const char *value, void *cb)
706 {
707         if (!strcmp(var, "stash.showstat")) {
708                 show_stat = git_config_bool(var, value);
709                 return 0;
710         }
711         if (!strcmp(var, "stash.showpatch")) {
712                 show_patch = git_config_bool(var, value);
713                 return 0;
714         }
715         return git_default_config(var, value, cb);
716 }
717
718 static int show_stash(int argc, const char **argv, const char *prefix)
719 {
720         int i;
721         int ret = 0;
722         struct stash_info info;
723         struct rev_info rev;
724         struct argv_array stash_args = ARGV_ARRAY_INIT;
725         struct argv_array revision_args = ARGV_ARRAY_INIT;
726         struct option options[] = {
727                 OPT_END()
728         };
729
730         init_diff_ui_defaults();
731         git_config(git_diff_ui_config, NULL);
732         init_revisions(&rev, prefix);
733
734         argv_array_push(&revision_args, argv[0]);
735         for (i = 1; i < argc; i++) {
736                 if (argv[i][0] != '-')
737                         argv_array_push(&stash_args, argv[i]);
738                 else
739                         argv_array_push(&revision_args, argv[i]);
740         }
741
742         ret = get_stash_info(&info, stash_args.argc, stash_args.argv);
743         argv_array_clear(&stash_args);
744         if (ret)
745                 return -1;
746
747         /*
748          * The config settings are applied only if there are not passed
749          * any options.
750          */
751         if (revision_args.argc == 1) {
752                 git_config(git_stash_config, NULL);
753                 if (show_stat)
754                         rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
755
756                 if (show_patch)
757                         rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
758
759                 if (!show_stat && !show_patch) {
760                         free_stash_info(&info);
761                         return 0;
762                 }
763         }
764
765         argc = setup_revisions(revision_args.argc, revision_args.argv, &rev, NULL);
766         if (argc > 1) {
767                 free_stash_info(&info);
768                 usage_with_options(git_stash_show_usage, options);
769         }
770         if (!rev.diffopt.output_format) {
771                 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
772                 diff_setup_done(&rev.diffopt);
773         }
774
775         rev.diffopt.flags.recursive = 1;
776         setup_diff_pager(&rev.diffopt);
777         diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
778         log_tree_diff_flush(&rev);
779
780         free_stash_info(&info);
781         return diff_result_code(&rev.diffopt, 0);
782 }
783
784 static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
785                           int quiet)
786 {
787         if (!stash_msg)
788                 stash_msg = "Created via \"git stash store\".";
789
790         if (update_ref(stash_msg, ref_stash, w_commit, NULL,
791                        REF_FORCE_CREATE_REFLOG,
792                        quiet ? UPDATE_REFS_QUIET_ON_ERR :
793                        UPDATE_REFS_MSG_ON_ERR)) {
794                 if (!quiet) {
795                         fprintf_ln(stderr, _("Cannot update %s with %s"),
796                                    ref_stash, oid_to_hex(w_commit));
797                 }
798                 return -1;
799         }
800
801         return 0;
802 }
803
804 static int store_stash(int argc, const char **argv, const char *prefix)
805 {
806         int quiet = 0;
807         const char *stash_msg = NULL;
808         struct object_id obj;
809         struct object_context dummy;
810         struct option options[] = {
811                 OPT__QUIET(&quiet, N_("be quiet")),
812                 OPT_STRING('m', "message", &stash_msg, "message",
813                            N_("stash message")),
814                 OPT_END()
815         };
816
817         argc = parse_options(argc, argv, prefix, options,
818                              git_stash_store_usage,
819                              PARSE_OPT_KEEP_UNKNOWN);
820
821         if (argc != 1) {
822                 if (!quiet)
823                         fprintf_ln(stderr, _("\"git stash store\" requires one "
824                                              "<commit> argument"));
825                 return -1;
826         }
827
828         if (get_oid_with_context(the_repository,
829                                  argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
830                                  &dummy)) {
831                 if (!quiet)
832                         fprintf_ln(stderr, _("Cannot update %s with %s"),
833                                              ref_stash, argv[0]);
834                 return -1;
835         }
836
837         return do_store_stash(&obj, stash_msg, quiet);
838 }
839
840 static void add_pathspecs(struct argv_array *args,
841                           const struct pathspec *ps) {
842         int i;
843
844         for (i = 0; i < ps->nr; i++)
845                 argv_array_push(args, ps->items[i].original);
846 }
847
848 /*
849  * `untracked_files` will be filled with the names of untracked files.
850  * The return value is:
851  *
852  * = 0 if there are not any untracked files
853  * > 0 if there are untracked files
854  */
855 static int get_untracked_files(const struct pathspec *ps, int include_untracked,
856                                struct strbuf *untracked_files)
857 {
858         int i;
859         int max_len;
860         int found = 0;
861         char *seen;
862         struct dir_struct dir;
863
864         memset(&dir, 0, sizeof(dir));
865         if (include_untracked != INCLUDE_ALL_FILES)
866                 setup_standard_excludes(&dir);
867
868         seen = xcalloc(ps->nr, 1);
869
870         max_len = fill_directory(&dir, the_repository->index, ps);
871         for (i = 0; i < dir.nr; i++) {
872                 struct dir_entry *ent = dir.entries[i];
873                 if (dir_path_match(&the_index, ent, ps, max_len, seen)) {
874                         found++;
875                         strbuf_addstr(untracked_files, ent->name);
876                         /* NUL-terminate: will be fed to update-index -z */
877                         strbuf_addch(untracked_files, '\0');
878                 }
879                 free(ent);
880         }
881
882         free(seen);
883         free(dir.entries);
884         free(dir.ignored);
885         clear_directory(&dir);
886         return found;
887 }
888
889 /*
890  * The return value of `check_changes_tracked_files()` can be:
891  *
892  * < 0 if there was an error
893  * = 0 if there are no changes.
894  * > 0 if there are changes.
895  */
896 static int check_changes_tracked_files(const struct pathspec *ps)
897 {
898         int result;
899         struct rev_info rev;
900         struct object_id dummy;
901         int ret = 0;
902
903         /* No initial commit. */
904         if (get_oid("HEAD", &dummy))
905                 return -1;
906
907         if (read_cache() < 0)
908                 return -1;
909
910         init_revisions(&rev, NULL);
911         copy_pathspec(&rev.prune_data, ps);
912
913         rev.diffopt.flags.quick = 1;
914         rev.diffopt.flags.ignore_submodules = 1;
915         rev.abbrev = 0;
916
917         add_head_to_pending(&rev);
918         diff_setup_done(&rev.diffopt);
919
920         result = run_diff_index(&rev, 1);
921         if (diff_result_code(&rev.diffopt, result)) {
922                 ret = 1;
923                 goto done;
924         }
925
926         object_array_clear(&rev.pending);
927         result = run_diff_files(&rev, 0);
928         if (diff_result_code(&rev.diffopt, result)) {
929                 ret = 1;
930                 goto done;
931         }
932
933 done:
934         clear_pathspec(&rev.prune_data);
935         return ret;
936 }
937
938 /*
939  * The function will fill `untracked_files` with the names of untracked files
940  * It will return 1 if there were any changes and 0 if there were not.
941  */
942 static int check_changes(const struct pathspec *ps, int include_untracked,
943                          struct strbuf *untracked_files)
944 {
945         int ret = 0;
946         if (check_changes_tracked_files(ps))
947                 ret = 1;
948
949         if (include_untracked && get_untracked_files(ps, include_untracked,
950                                                      untracked_files))
951                 ret = 1;
952
953         return ret;
954 }
955
956 static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
957                                 struct strbuf files)
958 {
959         int ret = 0;
960         struct strbuf untracked_msg = STRBUF_INIT;
961         struct child_process cp_upd_index = CHILD_PROCESS_INIT;
962         struct index_state istate = { NULL };
963
964         cp_upd_index.git_cmd = 1;
965         argv_array_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
966                          "--remove", "--stdin", NULL);
967         argv_array_pushf(&cp_upd_index.env_array, "GIT_INDEX_FILE=%s",
968                          stash_index_path.buf);
969
970         strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
971         if (pipe_command(&cp_upd_index, files.buf, files.len, NULL, 0,
972                          NULL, 0)) {
973                 ret = -1;
974                 goto done;
975         }
976
977         if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
978                                 NULL)) {
979                 ret = -1;
980                 goto done;
981         }
982
983         if (commit_tree(untracked_msg.buf, untracked_msg.len,
984                         &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
985                 ret = -1;
986                 goto done;
987         }
988
989 done:
990         discard_index(&istate);
991         strbuf_release(&untracked_msg);
992         remove_path(stash_index_path.buf);
993         return ret;
994 }
995
996 static int stash_patch(struct stash_info *info, const struct pathspec *ps,
997                        struct strbuf *out_patch, int quiet)
998 {
999         int ret = 0;
1000         struct child_process cp_read_tree = CHILD_PROCESS_INIT;
1001         struct child_process cp_add_i = CHILD_PROCESS_INIT;
1002         struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
1003         struct index_state istate = { NULL };
1004
1005         remove_path(stash_index_path.buf);
1006
1007         cp_read_tree.git_cmd = 1;
1008         argv_array_pushl(&cp_read_tree.args, "read-tree", "HEAD", NULL);
1009         argv_array_pushf(&cp_read_tree.env_array, "GIT_INDEX_FILE=%s",
1010                          stash_index_path.buf);
1011         if (run_command(&cp_read_tree)) {
1012                 ret = -1;
1013                 goto done;
1014         }
1015
1016         /* Find out what the user wants. */
1017         cp_add_i.git_cmd = 1;
1018         argv_array_pushl(&cp_add_i.args, "add--interactive", "--patch=stash",
1019                          "--", NULL);
1020         add_pathspecs(&cp_add_i.args, ps);
1021         argv_array_pushf(&cp_add_i.env_array, "GIT_INDEX_FILE=%s",
1022                          stash_index_path.buf);
1023         if (run_command(&cp_add_i)) {
1024                 ret = -1;
1025                 goto done;
1026         }
1027
1028         /* State of the working tree. */
1029         if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1030                                 NULL)) {
1031                 ret = -1;
1032                 goto done;
1033         }
1034
1035         cp_diff_tree.git_cmd = 1;
1036         argv_array_pushl(&cp_diff_tree.args, "diff-tree", "-p", "HEAD",
1037                          oid_to_hex(&info->w_tree), "--", NULL);
1038         if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1039                 ret = -1;
1040                 goto done;
1041         }
1042
1043         if (!out_patch->len) {
1044                 if (!quiet)
1045                         fprintf_ln(stderr, _("No changes selected"));
1046                 ret = 1;
1047         }
1048
1049 done:
1050         discard_index(&istate);
1051         remove_path(stash_index_path.buf);
1052         return ret;
1053 }
1054
1055 static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
1056 {
1057         int ret = 0;
1058         struct rev_info rev;
1059         struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1060         struct strbuf diff_output = STRBUF_INIT;
1061         struct index_state istate = { NULL };
1062
1063         init_revisions(&rev, NULL);
1064         copy_pathspec(&rev.prune_data, ps);
1065
1066         set_alternate_index_output(stash_index_path.buf);
1067         if (reset_tree(&info->i_tree, 0, 0)) {
1068                 ret = -1;
1069                 goto done;
1070         }
1071         set_alternate_index_output(NULL);
1072
1073         rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1074         rev.diffopt.format_callback = add_diff_to_buf;
1075         rev.diffopt.format_callback_data = &diff_output;
1076
1077         if (read_cache_preload(&rev.diffopt.pathspec) < 0) {
1078                 ret = -1;
1079                 goto done;
1080         }
1081
1082         add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1083                            "");
1084         if (run_diff_index(&rev, 0)) {
1085                 ret = -1;
1086                 goto done;
1087         }
1088
1089         cp_upd_index.git_cmd = 1;
1090         argv_array_pushl(&cp_upd_index.args, "update-index",
1091                          "--ignore-skip-worktree-entries",
1092                          "-z", "--add", "--remove", "--stdin", NULL);
1093         argv_array_pushf(&cp_upd_index.env_array, "GIT_INDEX_FILE=%s",
1094                          stash_index_path.buf);
1095
1096         if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1097                          NULL, 0, NULL, 0)) {
1098                 ret = -1;
1099                 goto done;
1100         }
1101
1102         if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1103                                 NULL)) {
1104                 ret = -1;
1105                 goto done;
1106         }
1107
1108 done:
1109         discard_index(&istate);
1110         UNLEAK(rev);
1111         object_array_clear(&rev.pending);
1112         clear_pathspec(&rev.prune_data);
1113         strbuf_release(&diff_output);
1114         remove_path(stash_index_path.buf);
1115         return ret;
1116 }
1117
1118 static int do_create_stash(const struct pathspec *ps, struct strbuf *stash_msg_buf,
1119                            int include_untracked, int patch_mode,
1120                            struct stash_info *info, struct strbuf *patch,
1121                            int quiet)
1122 {
1123         int ret = 0;
1124         int flags = 0;
1125         int untracked_commit_option = 0;
1126         const char *head_short_sha1 = NULL;
1127         const char *branch_ref = NULL;
1128         const char *branch_name = "(no branch)";
1129         struct commit *head_commit = NULL;
1130         struct commit_list *parents = NULL;
1131         struct strbuf msg = STRBUF_INIT;
1132         struct strbuf commit_tree_label = STRBUF_INIT;
1133         struct strbuf untracked_files = STRBUF_INIT;
1134
1135         prepare_fallback_ident("git stash", "git@stash");
1136
1137         read_cache_preload(NULL);
1138         if (refresh_and_write_cache(REFRESH_QUIET, 0, 0) < 0) {
1139                 ret = -1;
1140                 goto done;
1141         }
1142
1143         if (get_oid("HEAD", &info->b_commit)) {
1144                 if (!quiet)
1145                         fprintf_ln(stderr, _("You do not have "
1146                                              "the initial commit yet"));
1147                 ret = -1;
1148                 goto done;
1149         } else {
1150                 head_commit = lookup_commit(the_repository, &info->b_commit);
1151         }
1152
1153         if (!check_changes(ps, include_untracked, &untracked_files)) {
1154                 ret = 1;
1155                 goto done;
1156         }
1157
1158         branch_ref = resolve_ref_unsafe("HEAD", 0, NULL, &flags);
1159         if (flags & REF_ISSYMREF)
1160                 branch_name = strrchr(branch_ref, '/') + 1;
1161         head_short_sha1 = find_unique_abbrev(&head_commit->object.oid,
1162                                              DEFAULT_ABBREV);
1163         strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1164         pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1165
1166         strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1167         commit_list_insert(head_commit, &parents);
1168         if (write_cache_as_tree(&info->i_tree, 0, NULL) ||
1169             commit_tree(commit_tree_label.buf, commit_tree_label.len,
1170                         &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1171                 if (!quiet)
1172                         fprintf_ln(stderr, _("Cannot save the current "
1173                                              "index state"));
1174                 ret = -1;
1175                 goto done;
1176         }
1177
1178         if (include_untracked) {
1179                 if (save_untracked_files(info, &msg, untracked_files)) {
1180                         if (!quiet)
1181                                 fprintf_ln(stderr, _("Cannot save "
1182                                                      "the untracked files"));
1183                         ret = -1;
1184                         goto done;
1185                 }
1186                 untracked_commit_option = 1;
1187         }
1188         if (patch_mode) {
1189                 ret = stash_patch(info, ps, patch, quiet);
1190                 if (ret < 0) {
1191                         if (!quiet)
1192                                 fprintf_ln(stderr, _("Cannot save the current "
1193                                                      "worktree state"));
1194                         goto done;
1195                 } else if (ret > 0) {
1196                         goto done;
1197                 }
1198         } else {
1199                 if (stash_working_tree(info, ps)) {
1200                         if (!quiet)
1201                                 fprintf_ln(stderr, _("Cannot save the current "
1202                                                      "worktree state"));
1203                         ret = -1;
1204                         goto done;
1205                 }
1206         }
1207
1208         if (!stash_msg_buf->len)
1209                 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1210         else
1211                 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1212
1213         /*
1214          * `parents` will be empty after calling `commit_tree()`, so there is
1215          * no need to call `free_commit_list()`
1216          */
1217         parents = NULL;
1218         if (untracked_commit_option)
1219                 commit_list_insert(lookup_commit(the_repository,
1220                                                  &info->u_commit),
1221                                    &parents);
1222         commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1223                            &parents);
1224         commit_list_insert(head_commit, &parents);
1225
1226         if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1227                         parents, &info->w_commit, NULL, NULL)) {
1228                 if (!quiet)
1229                         fprintf_ln(stderr, _("Cannot record "
1230                                              "working tree state"));
1231                 ret = -1;
1232                 goto done;
1233         }
1234
1235 done:
1236         strbuf_release(&commit_tree_label);
1237         strbuf_release(&msg);
1238         strbuf_release(&untracked_files);
1239         return ret;
1240 }
1241
1242 static int create_stash(int argc, const char **argv, const char *prefix)
1243 {
1244         int ret = 0;
1245         struct strbuf stash_msg_buf = STRBUF_INIT;
1246         struct stash_info info;
1247         struct pathspec ps;
1248
1249         /* Starting with argv[1], since argv[0] is "create" */
1250         strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
1251
1252         memset(&ps, 0, sizeof(ps));
1253         if (!check_changes_tracked_files(&ps))
1254                 return 0;
1255
1256         ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, &info,
1257                               NULL, 0);
1258         if (!ret)
1259                 printf_ln("%s", oid_to_hex(&info.w_commit));
1260
1261         strbuf_release(&stash_msg_buf);
1262         return ret;
1263 }
1264
1265 static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int quiet,
1266                          int keep_index, int patch_mode, int include_untracked)
1267 {
1268         int ret = 0;
1269         struct stash_info info;
1270         struct strbuf patch = STRBUF_INIT;
1271         struct strbuf stash_msg_buf = STRBUF_INIT;
1272         struct strbuf untracked_files = STRBUF_INIT;
1273
1274         if (patch_mode && keep_index == -1)
1275                 keep_index = 1;
1276
1277         if (patch_mode && include_untracked) {
1278                 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1279                                      " or --all at the same time"));
1280                 ret = -1;
1281                 goto done;
1282         }
1283
1284         read_cache_preload(NULL);
1285         if (!include_untracked && ps->nr) {
1286                 int i;
1287                 char *ps_matched = xcalloc(ps->nr, 1);
1288
1289                 for (i = 0; i < active_nr; i++)
1290                         ce_path_match(&the_index, active_cache[i], ps,
1291                                       ps_matched);
1292
1293                 if (report_path_error(ps_matched, ps)) {
1294                         fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1295                         ret = -1;
1296                         free(ps_matched);
1297                         goto done;
1298                 }
1299                 free(ps_matched);
1300         }
1301
1302         if (refresh_and_write_cache(REFRESH_QUIET, 0, 0)) {
1303                 ret = -1;
1304                 goto done;
1305         }
1306
1307         if (!check_changes(ps, include_untracked, &untracked_files)) {
1308                 if (!quiet)
1309                         printf_ln(_("No local changes to save"));
1310                 goto done;
1311         }
1312
1313         if (!reflog_exists(ref_stash) && do_clear_stash()) {
1314                 ret = -1;
1315                 if (!quiet)
1316                         fprintf_ln(stderr, _("Cannot initialize stash"));
1317                 goto done;
1318         }
1319
1320         if (stash_msg)
1321                 strbuf_addstr(&stash_msg_buf, stash_msg);
1322         if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode,
1323                             &info, &patch, quiet)) {
1324                 ret = -1;
1325                 goto done;
1326         }
1327
1328         if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1329                 ret = -1;
1330                 if (!quiet)
1331                         fprintf_ln(stderr, _("Cannot save the current status"));
1332                 goto done;
1333         }
1334
1335         if (!quiet)
1336                 printf_ln(_("Saved working directory and index state %s"),
1337                           stash_msg_buf.buf);
1338
1339         if (!patch_mode) {
1340                 if (include_untracked && !ps->nr) {
1341                         struct child_process cp = CHILD_PROCESS_INIT;
1342
1343                         cp.git_cmd = 1;
1344                         argv_array_pushl(&cp.args, "clean", "--force",
1345                                          "--quiet", "-d", NULL);
1346                         if (include_untracked == INCLUDE_ALL_FILES)
1347                                 argv_array_push(&cp.args, "-x");
1348                         if (run_command(&cp)) {
1349                                 ret = -1;
1350                                 goto done;
1351                         }
1352                 }
1353                 discard_cache();
1354                 if (ps->nr) {
1355                         struct child_process cp_add = CHILD_PROCESS_INIT;
1356                         struct child_process cp_diff = CHILD_PROCESS_INIT;
1357                         struct child_process cp_apply = CHILD_PROCESS_INIT;
1358                         struct strbuf out = STRBUF_INIT;
1359
1360                         cp_add.git_cmd = 1;
1361                         argv_array_push(&cp_add.args, "add");
1362                         if (!include_untracked)
1363                                 argv_array_push(&cp_add.args, "-u");
1364                         if (include_untracked == INCLUDE_ALL_FILES)
1365                                 argv_array_push(&cp_add.args, "--force");
1366                         argv_array_push(&cp_add.args, "--");
1367                         add_pathspecs(&cp_add.args, ps);
1368                         if (run_command(&cp_add)) {
1369                                 ret = -1;
1370                                 goto done;
1371                         }
1372
1373                         cp_diff.git_cmd = 1;
1374                         argv_array_pushl(&cp_diff.args, "diff-index", "-p",
1375                                          "--cached", "--binary", "HEAD", "--",
1376                                          NULL);
1377                         add_pathspecs(&cp_diff.args, ps);
1378                         if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1379                                 ret = -1;
1380                                 goto done;
1381                         }
1382
1383                         cp_apply.git_cmd = 1;
1384                         argv_array_pushl(&cp_apply.args, "apply", "--index",
1385                                          "-R", NULL);
1386                         if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1387                                          NULL, 0)) {
1388                                 ret = -1;
1389                                 goto done;
1390                         }
1391                 } else {
1392                         struct child_process cp = CHILD_PROCESS_INIT;
1393                         cp.git_cmd = 1;
1394                         argv_array_pushl(&cp.args, "reset", "--hard", "-q",
1395                                          "--no-recurse-submodules", NULL);
1396                         if (run_command(&cp)) {
1397                                 ret = -1;
1398                                 goto done;
1399                         }
1400                 }
1401
1402                 if (keep_index == 1 && !is_null_oid(&info.i_tree)) {
1403                         struct child_process cp = CHILD_PROCESS_INIT;
1404
1405                         cp.git_cmd = 1;
1406                         argv_array_pushl(&cp.args, "checkout", "--no-overlay",
1407                                          oid_to_hex(&info.i_tree), "--", NULL);
1408                         if (!ps->nr)
1409                                 argv_array_push(&cp.args, ":/");
1410                         else
1411                                 add_pathspecs(&cp.args, ps);
1412                         if (run_command(&cp)) {
1413                                 ret = -1;
1414                                 goto done;
1415                         }
1416                 }
1417                 goto done;
1418         } else {
1419                 struct child_process cp = CHILD_PROCESS_INIT;
1420
1421                 cp.git_cmd = 1;
1422                 argv_array_pushl(&cp.args, "apply", "-R", NULL);
1423
1424                 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1425                         if (!quiet)
1426                                 fprintf_ln(stderr, _("Cannot remove "
1427                                                      "worktree changes"));
1428                         ret = -1;
1429                         goto done;
1430                 }
1431
1432                 if (keep_index < 1) {
1433                         struct child_process cp = CHILD_PROCESS_INIT;
1434
1435                         cp.git_cmd = 1;
1436                         argv_array_pushl(&cp.args, "reset", "-q", "--", NULL);
1437                         add_pathspecs(&cp.args, ps);
1438                         if (run_command(&cp)) {
1439                                 ret = -1;
1440                                 goto done;
1441                         }
1442                 }
1443                 goto done;
1444         }
1445
1446 done:
1447         strbuf_release(&stash_msg_buf);
1448         return ret;
1449 }
1450
1451 static int push_stash(int argc, const char **argv, const char *prefix)
1452 {
1453         int keep_index = -1;
1454         int patch_mode = 0;
1455         int include_untracked = 0;
1456         int quiet = 0;
1457         const char *stash_msg = NULL;
1458         struct pathspec ps;
1459         struct option options[] = {
1460                 OPT_BOOL('k', "keep-index", &keep_index,
1461                          N_("keep index")),
1462                 OPT_BOOL('p', "patch", &patch_mode,
1463                          N_("stash in patch mode")),
1464                 OPT__QUIET(&quiet, N_("quiet mode")),
1465                 OPT_BOOL('u', "include-untracked", &include_untracked,
1466                          N_("include untracked files in stash")),
1467                 OPT_SET_INT('a', "all", &include_untracked,
1468                             N_("include ignore files"), 2),
1469                 OPT_STRING('m', "message", &stash_msg, N_("message"),
1470                            N_("stash message")),
1471                 OPT_END()
1472         };
1473
1474         if (argc)
1475                 argc = parse_options(argc, argv, prefix, options,
1476                                      git_stash_push_usage,
1477                                      0);
1478
1479         parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
1480                        prefix, argv);
1481         return do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
1482                              include_untracked);
1483 }
1484
1485 static int save_stash(int argc, const char **argv, const char *prefix)
1486 {
1487         int keep_index = -1;
1488         int patch_mode = 0;
1489         int include_untracked = 0;
1490         int quiet = 0;
1491         int ret = 0;
1492         const char *stash_msg = NULL;
1493         struct pathspec ps;
1494         struct strbuf stash_msg_buf = STRBUF_INIT;
1495         struct option options[] = {
1496                 OPT_BOOL('k', "keep-index", &keep_index,
1497                          N_("keep index")),
1498                 OPT_BOOL('p', "patch", &patch_mode,
1499                          N_("stash in patch mode")),
1500                 OPT__QUIET(&quiet, N_("quiet mode")),
1501                 OPT_BOOL('u', "include-untracked", &include_untracked,
1502                          N_("include untracked files in stash")),
1503                 OPT_SET_INT('a', "all", &include_untracked,
1504                             N_("include ignore files"), 2),
1505                 OPT_STRING('m', "message", &stash_msg, "message",
1506                            N_("stash message")),
1507                 OPT_END()
1508         };
1509
1510         argc = parse_options(argc, argv, prefix, options,
1511                              git_stash_save_usage,
1512                              PARSE_OPT_KEEP_DASHDASH);
1513
1514         if (argc)
1515                 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
1516
1517         memset(&ps, 0, sizeof(ps));
1518         ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
1519                             patch_mode, include_untracked);
1520
1521         strbuf_release(&stash_msg_buf);
1522         return ret;
1523 }
1524
1525 static int use_builtin_stash(void)
1526 {
1527         struct child_process cp = CHILD_PROCESS_INIT;
1528         struct strbuf out = STRBUF_INIT;
1529         int ret, env = git_env_bool("GIT_TEST_STASH_USE_BUILTIN", -1);
1530
1531         if (env != -1)
1532                 return env;
1533
1534         argv_array_pushl(&cp.args,
1535                          "config", "--bool", "stash.usebuiltin", NULL);
1536         cp.git_cmd = 1;
1537         if (capture_command(&cp, &out, 6)) {
1538                 strbuf_release(&out);
1539                 return 1;
1540         }
1541
1542         strbuf_trim(&out);
1543         ret = !strcmp("true", out.buf);
1544         strbuf_release(&out);
1545         return ret;
1546 }
1547
1548 int cmd_stash(int argc, const char **argv, const char *prefix)
1549 {
1550         int i = -1;
1551         pid_t pid = getpid();
1552         const char *index_file;
1553         struct argv_array args = ARGV_ARRAY_INIT;
1554
1555         struct option options[] = {
1556                 OPT_END()
1557         };
1558
1559         if (!use_builtin_stash()) {
1560                 const char *path = mkpath("%s/git-legacy-stash",
1561                                           git_exec_path());
1562
1563                 if (sane_execvp(path, (char **)argv) < 0)
1564                         die_errno(_("could not exec %s"), path);
1565                 else
1566                         BUG("sane_execvp() returned???");
1567         }
1568
1569         prefix = setup_git_directory();
1570         trace_repo_setup(prefix);
1571         setup_work_tree();
1572
1573         git_config(git_diff_basic_config, NULL);
1574
1575         argc = parse_options(argc, argv, prefix, options, git_stash_usage,
1576                              PARSE_OPT_KEEP_UNKNOWN | PARSE_OPT_KEEP_DASHDASH);
1577
1578         index_file = get_index_file();
1579         strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
1580                     (uintmax_t)pid);
1581
1582         if (!argc)
1583                 return !!push_stash(0, NULL, prefix);
1584         else if (!strcmp(argv[0], "apply"))
1585                 return !!apply_stash(argc, argv, prefix);
1586         else if (!strcmp(argv[0], "clear"))
1587                 return !!clear_stash(argc, argv, prefix);
1588         else if (!strcmp(argv[0], "drop"))
1589                 return !!drop_stash(argc, argv, prefix);
1590         else if (!strcmp(argv[0], "pop"))
1591                 return !!pop_stash(argc, argv, prefix);
1592         else if (!strcmp(argv[0], "branch"))
1593                 return !!branch_stash(argc, argv, prefix);
1594         else if (!strcmp(argv[0], "list"))
1595                 return !!list_stash(argc, argv, prefix);
1596         else if (!strcmp(argv[0], "show"))
1597                 return !!show_stash(argc, argv, prefix);
1598         else if (!strcmp(argv[0], "store"))
1599                 return !!store_stash(argc, argv, prefix);
1600         else if (!strcmp(argv[0], "create"))
1601                 return !!create_stash(argc, argv, prefix);
1602         else if (!strcmp(argv[0], "push"))
1603                 return !!push_stash(argc, argv, prefix);
1604         else if (!strcmp(argv[0], "save"))
1605                 return !!save_stash(argc, argv, prefix);
1606         else if (*argv[0] != '-')
1607                 usage_msg_opt(xstrfmt(_("unknown subcommand: %s"), argv[0]),
1608                               git_stash_usage, options);
1609
1610         if (strcmp(argv[0], "-p")) {
1611                 while (++i < argc && strcmp(argv[i], "--")) {
1612                         /*
1613                          * `akpqu` is a string which contains all short options,
1614                          * except `-m` which is verified separately.
1615                          */
1616                         if ((strlen(argv[i]) == 2) && *argv[i] == '-' &&
1617                             strchr("akpqu", argv[i][1]))
1618                                 continue;
1619
1620                         if (!strcmp(argv[i], "--all") ||
1621                             !strcmp(argv[i], "--keep-index") ||
1622                             !strcmp(argv[i], "--no-keep-index") ||
1623                             !strcmp(argv[i], "--patch") ||
1624                             !strcmp(argv[i], "--quiet") ||
1625                             !strcmp(argv[i], "--include-untracked"))
1626                                 continue;
1627
1628                         /*
1629                          * `-m` and `--message=` are verified separately because
1630                          * they need to be immediately followed by a string
1631                          * (i.e.`-m"foobar"` or `--message="foobar"`).
1632                          */
1633                         if (starts_with(argv[i], "-m") ||
1634                             starts_with(argv[i], "--message="))
1635                                 continue;
1636
1637                         usage_with_options(git_stash_usage, options);
1638                 }
1639         }
1640
1641         argv_array_push(&args, "push");
1642         argv_array_pushv(&args, argv);
1643         return !!push_stash(args.argc, args.argv, prefix);
1644 }