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