stash: setup default diff output format if necessary
[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         if (!rev.diffopt.output_format) {
764                 rev.diffopt.output_format = DIFF_FORMAT_PATCH;
765                 diff_setup_done(&rev.diffopt);
766         }
767
768         rev.diffopt.flags.recursive = 1;
769         setup_diff_pager(&rev.diffopt);
770         diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
771         log_tree_diff_flush(&rev);
772
773         free_stash_info(&info);
774         return diff_result_code(&rev.diffopt, 0);
775 }
776
777 static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
778                           int quiet)
779 {
780         if (!stash_msg)
781                 stash_msg = "Created via \"git stash store\".";
782
783         if (update_ref(stash_msg, ref_stash, w_commit, NULL,
784                        REF_FORCE_CREATE_REFLOG,
785                        quiet ? UPDATE_REFS_QUIET_ON_ERR :
786                        UPDATE_REFS_MSG_ON_ERR)) {
787                 if (!quiet) {
788                         fprintf_ln(stderr, _("Cannot update %s with %s"),
789                                    ref_stash, oid_to_hex(w_commit));
790                 }
791                 return -1;
792         }
793
794         return 0;
795 }
796
797 static int store_stash(int argc, const char **argv, const char *prefix)
798 {
799         int quiet = 0;
800         const char *stash_msg = NULL;
801         struct object_id obj;
802         struct object_context dummy;
803         struct option options[] = {
804                 OPT__QUIET(&quiet, N_("be quiet")),
805                 OPT_STRING('m', "message", &stash_msg, "message",
806                            N_("stash message")),
807                 OPT_END()
808         };
809
810         argc = parse_options(argc, argv, prefix, options,
811                              git_stash_store_usage,
812                              PARSE_OPT_KEEP_UNKNOWN);
813
814         if (argc != 1) {
815                 if (!quiet)
816                         fprintf_ln(stderr, _("\"git stash store\" requires one "
817                                              "<commit> argument"));
818                 return -1;
819         }
820
821         if (get_oid_with_context(argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
822                                  &dummy)) {
823                 if (!quiet)
824                         fprintf_ln(stderr, _("Cannot update %s with %s"),
825                                              ref_stash, argv[0]);
826                 return -1;
827         }
828
829         return do_store_stash(&obj, stash_msg, quiet);
830 }
831
832 static void add_pathspecs(struct argv_array *args,
833                           struct pathspec ps) {
834         int i;
835
836         for (i = 0; i < ps.nr; i++)
837                 argv_array_push(args, ps.items[i].match);
838 }
839
840 /*
841  * `untracked_files` will be filled with the names of untracked files.
842  * The return value is:
843  *
844  * = 0 if there are not any untracked files
845  * > 0 if there are untracked files
846  */
847 static int get_untracked_files(struct pathspec ps, int include_untracked,
848                                struct strbuf *untracked_files)
849 {
850         int i;
851         int max_len;
852         int found = 0;
853         char *seen;
854         struct dir_struct dir;
855
856         memset(&dir, 0, sizeof(dir));
857         if (include_untracked != INCLUDE_ALL_FILES)
858                 setup_standard_excludes(&dir);
859
860         seen = xcalloc(ps.nr, 1);
861
862         max_len = fill_directory(&dir, the_repository->index, &ps);
863         for (i = 0; i < dir.nr; i++) {
864                 struct dir_entry *ent = dir.entries[i];
865                 if (dir_path_match(&the_index, ent, &ps, max_len, seen)) {
866                         found++;
867                         strbuf_addstr(untracked_files, ent->name);
868                         /* NUL-terminate: will be fed to update-index -z */
869                         strbuf_addch(untracked_files, '\0');
870                 }
871                 free(ent);
872         }
873
874         free(seen);
875         free(dir.entries);
876         free(dir.ignored);
877         clear_directory(&dir);
878         return found;
879 }
880
881 /*
882  * The return value of `check_changes_tracked_files()` can be:
883  *
884  * < 0 if there was an error
885  * = 0 if there are no changes.
886  * > 0 if there are changes.
887  */
888 static int check_changes_tracked_files(struct pathspec ps)
889 {
890         int result;
891         struct rev_info rev;
892         struct object_id dummy;
893
894         /* No initial commit. */
895         if (get_oid("HEAD", &dummy))
896                 return -1;
897
898         if (read_cache() < 0)
899                 return -1;
900
901         init_revisions(&rev, NULL);
902         rev.prune_data = ps;
903
904         rev.diffopt.flags.quick = 1;
905         rev.diffopt.flags.ignore_submodules = 1;
906         rev.abbrev = 0;
907
908         add_head_to_pending(&rev);
909         diff_setup_done(&rev.diffopt);
910
911         result = run_diff_index(&rev, 1);
912         if (diff_result_code(&rev.diffopt, result))
913                 return 1;
914
915         object_array_clear(&rev.pending);
916         result = run_diff_files(&rev, 0);
917         if (diff_result_code(&rev.diffopt, result))
918                 return 1;
919
920         return 0;
921 }
922
923 /*
924  * The function will fill `untracked_files` with the names of untracked files
925  * It will return 1 if there were any changes and 0 if there were not.
926  */
927 static int check_changes(struct pathspec ps, int include_untracked,
928                          struct strbuf *untracked_files)
929 {
930         int ret = 0;
931         if (check_changes_tracked_files(ps))
932                 ret = 1;
933
934         if (include_untracked && get_untracked_files(ps, include_untracked,
935                                                      untracked_files))
936                 ret = 1;
937
938         return ret;
939 }
940
941 static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
942                                 struct strbuf files)
943 {
944         int ret = 0;
945         struct strbuf untracked_msg = STRBUF_INIT;
946         struct child_process cp_upd_index = CHILD_PROCESS_INIT;
947         struct index_state istate = { NULL };
948
949         cp_upd_index.git_cmd = 1;
950         argv_array_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
951                          "--remove", "--stdin", NULL);
952         argv_array_pushf(&cp_upd_index.env_array, "GIT_INDEX_FILE=%s",
953                          stash_index_path.buf);
954
955         strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
956         if (pipe_command(&cp_upd_index, files.buf, files.len, NULL, 0,
957                          NULL, 0)) {
958                 ret = -1;
959                 goto done;
960         }
961
962         if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
963                                 NULL)) {
964                 ret = -1;
965                 goto done;
966         }
967
968         if (commit_tree(untracked_msg.buf, untracked_msg.len,
969                         &info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
970                 ret = -1;
971                 goto done;
972         }
973
974 done:
975         discard_index(&istate);
976         strbuf_release(&untracked_msg);
977         remove_path(stash_index_path.buf);
978         return ret;
979 }
980
981 static int stash_patch(struct stash_info *info, struct pathspec ps,
982                        struct strbuf *out_patch, int quiet)
983 {
984         int ret = 0;
985         struct child_process cp_read_tree = CHILD_PROCESS_INIT;
986         struct child_process cp_add_i = CHILD_PROCESS_INIT;
987         struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
988         struct index_state istate = { NULL };
989
990         remove_path(stash_index_path.buf);
991
992         cp_read_tree.git_cmd = 1;
993         argv_array_pushl(&cp_read_tree.args, "read-tree", "HEAD", NULL);
994         argv_array_pushf(&cp_read_tree.env_array, "GIT_INDEX_FILE=%s",
995                          stash_index_path.buf);
996         if (run_command(&cp_read_tree)) {
997                 ret = -1;
998                 goto done;
999         }
1000
1001         /* Find out what the user wants. */
1002         cp_add_i.git_cmd = 1;
1003         argv_array_pushl(&cp_add_i.args, "add--interactive", "--patch=stash",
1004                          "--", NULL);
1005         add_pathspecs(&cp_add_i.args, ps);
1006         argv_array_pushf(&cp_add_i.env_array, "GIT_INDEX_FILE=%s",
1007                          stash_index_path.buf);
1008         if (run_command(&cp_add_i)) {
1009                 ret = -1;
1010                 goto done;
1011         }
1012
1013         /* State of the working tree. */
1014         if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1015                                 NULL)) {
1016                 ret = -1;
1017                 goto done;
1018         }
1019
1020         cp_diff_tree.git_cmd = 1;
1021         argv_array_pushl(&cp_diff_tree.args, "diff-tree", "-p", "HEAD",
1022                          oid_to_hex(&info->w_tree), "--", NULL);
1023         if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
1024                 ret = -1;
1025                 goto done;
1026         }
1027
1028         if (!out_patch->len) {
1029                 if (!quiet)
1030                         fprintf_ln(stderr, _("No changes selected"));
1031                 ret = 1;
1032         }
1033
1034 done:
1035         discard_index(&istate);
1036         remove_path(stash_index_path.buf);
1037         return ret;
1038 }
1039
1040 static int stash_working_tree(struct stash_info *info, struct pathspec ps)
1041 {
1042         int ret = 0;
1043         struct rev_info rev;
1044         struct child_process cp_upd_index = CHILD_PROCESS_INIT;
1045         struct strbuf diff_output = STRBUF_INIT;
1046         struct index_state istate = { NULL };
1047
1048         init_revisions(&rev, NULL);
1049
1050         set_alternate_index_output(stash_index_path.buf);
1051         if (reset_tree(&info->i_tree, 0, 0)) {
1052                 ret = -1;
1053                 goto done;
1054         }
1055         set_alternate_index_output(NULL);
1056
1057         rev.prune_data = ps;
1058         rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
1059         rev.diffopt.format_callback = add_diff_to_buf;
1060         rev.diffopt.format_callback_data = &diff_output;
1061
1062         if (read_cache_preload(&rev.diffopt.pathspec) < 0) {
1063                 ret = -1;
1064                 goto done;
1065         }
1066
1067         add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
1068                            "");
1069         if (run_diff_index(&rev, 0)) {
1070                 ret = -1;
1071                 goto done;
1072         }
1073
1074         cp_upd_index.git_cmd = 1;
1075         argv_array_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
1076                          "--remove", "--stdin", NULL);
1077         argv_array_pushf(&cp_upd_index.env_array, "GIT_INDEX_FILE=%s",
1078                          stash_index_path.buf);
1079
1080         if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
1081                          NULL, 0, NULL, 0)) {
1082                 ret = -1;
1083                 goto done;
1084         }
1085
1086         if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
1087                                 NULL)) {
1088                 ret = -1;
1089                 goto done;
1090         }
1091
1092 done:
1093         discard_index(&istate);
1094         UNLEAK(rev);
1095         object_array_clear(&rev.pending);
1096         strbuf_release(&diff_output);
1097         remove_path(stash_index_path.buf);
1098         return ret;
1099 }
1100
1101 static int do_create_stash(struct pathspec ps, struct strbuf *stash_msg_buf,
1102                            int include_untracked, int patch_mode,
1103                            struct stash_info *info, struct strbuf *patch,
1104                            int quiet)
1105 {
1106         int ret = 0;
1107         int flags = 0;
1108         int untracked_commit_option = 0;
1109         const char *head_short_sha1 = NULL;
1110         const char *branch_ref = NULL;
1111         const char *branch_name = "(no branch)";
1112         struct commit *head_commit = NULL;
1113         struct commit_list *parents = NULL;
1114         struct strbuf msg = STRBUF_INIT;
1115         struct strbuf commit_tree_label = STRBUF_INIT;
1116         struct strbuf untracked_files = STRBUF_INIT;
1117
1118         prepare_fallback_ident("git stash", "git@stash");
1119
1120         read_cache_preload(NULL);
1121         refresh_cache(REFRESH_QUIET);
1122
1123         if (get_oid("HEAD", &info->b_commit)) {
1124                 if (!quiet)
1125                         fprintf_ln(stderr, _("You do not have "
1126                                              "the initial commit yet"));
1127                 ret = -1;
1128                 goto done;
1129         } else {
1130                 head_commit = lookup_commit(the_repository, &info->b_commit);
1131         }
1132
1133         if (!check_changes(ps, include_untracked, &untracked_files)) {
1134                 ret = 1;
1135                 goto done;
1136         }
1137
1138         branch_ref = resolve_ref_unsafe("HEAD", 0, NULL, &flags);
1139         if (flags & REF_ISSYMREF)
1140                 branch_name = strrchr(branch_ref, '/') + 1;
1141         head_short_sha1 = find_unique_abbrev(&head_commit->object.oid,
1142                                              DEFAULT_ABBREV);
1143         strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
1144         pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
1145
1146         strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
1147         commit_list_insert(head_commit, &parents);
1148         if (write_cache_as_tree(&info->i_tree, 0, NULL) ||
1149             commit_tree(commit_tree_label.buf, commit_tree_label.len,
1150                         &info->i_tree, parents, &info->i_commit, NULL, NULL)) {
1151                 if (!quiet)
1152                         fprintf_ln(stderr, _("Cannot save the current "
1153                                              "index state"));
1154                 ret = -1;
1155                 goto done;
1156         }
1157
1158         if (include_untracked) {
1159                 if (save_untracked_files(info, &msg, untracked_files)) {
1160                         if (!quiet)
1161                                 fprintf_ln(stderr, _("Cannot save "
1162                                                      "the untracked files"));
1163                         ret = -1;
1164                         goto done;
1165                 }
1166                 untracked_commit_option = 1;
1167         }
1168         if (patch_mode) {
1169                 ret = stash_patch(info, ps, patch, quiet);
1170                 if (ret < 0) {
1171                         if (!quiet)
1172                                 fprintf_ln(stderr, _("Cannot save the current "
1173                                                      "worktree state"));
1174                         goto done;
1175                 } else if (ret > 0) {
1176                         goto done;
1177                 }
1178         } else {
1179                 if (stash_working_tree(info, ps)) {
1180                         if (!quiet)
1181                                 fprintf_ln(stderr, _("Cannot save the current "
1182                                                      "worktree state"));
1183                         ret = -1;
1184                         goto done;
1185                 }
1186         }
1187
1188         if (!stash_msg_buf->len)
1189                 strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
1190         else
1191                 strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
1192
1193         /*
1194          * `parents` will be empty after calling `commit_tree()`, so there is
1195          * no need to call `free_commit_list()`
1196          */
1197         parents = NULL;
1198         if (untracked_commit_option)
1199                 commit_list_insert(lookup_commit(the_repository,
1200                                                  &info->u_commit),
1201                                    &parents);
1202         commit_list_insert(lookup_commit(the_repository, &info->i_commit),
1203                            &parents);
1204         commit_list_insert(head_commit, &parents);
1205
1206         if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
1207                         parents, &info->w_commit, NULL, NULL)) {
1208                 if (!quiet)
1209                         fprintf_ln(stderr, _("Cannot record "
1210                                              "working tree state"));
1211                 ret = -1;
1212                 goto done;
1213         }
1214
1215 done:
1216         strbuf_release(&commit_tree_label);
1217         strbuf_release(&msg);
1218         strbuf_release(&untracked_files);
1219         return ret;
1220 }
1221
1222 static int create_stash(int argc, const char **argv, const char *prefix)
1223 {
1224         int ret = 0;
1225         struct strbuf stash_msg_buf = STRBUF_INIT;
1226         struct stash_info info;
1227         struct pathspec ps;
1228
1229         /* Starting with argv[1], since argv[0] is "create" */
1230         strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
1231
1232         memset(&ps, 0, sizeof(ps));
1233         if (!check_changes_tracked_files(ps))
1234                 return 0;
1235
1236         ret = do_create_stash(ps, &stash_msg_buf, 0, 0, &info,
1237                               NULL, 0);
1238         if (!ret)
1239                 printf_ln("%s", oid_to_hex(&info.w_commit));
1240
1241         strbuf_release(&stash_msg_buf);
1242         return ret;
1243 }
1244
1245 static int do_push_stash(struct pathspec ps, const char *stash_msg, int quiet,
1246                          int keep_index, int patch_mode, int include_untracked)
1247 {
1248         int ret = 0;
1249         struct stash_info info;
1250         struct strbuf patch = STRBUF_INIT;
1251         struct strbuf stash_msg_buf = STRBUF_INIT;
1252         struct strbuf untracked_files = STRBUF_INIT;
1253
1254         if (patch_mode && keep_index == -1)
1255                 keep_index = 1;
1256
1257         if (patch_mode && include_untracked) {
1258                 fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
1259                                      " or --all at the same time"));
1260                 ret = -1;
1261                 goto done;
1262         }
1263
1264         read_cache_preload(NULL);
1265         if (!include_untracked && ps.nr) {
1266                 int i;
1267                 char *ps_matched = xcalloc(ps.nr, 1);
1268
1269                 for (i = 0; i < active_nr; i++)
1270                         ce_path_match(&the_index, active_cache[i], &ps,
1271                                       ps_matched);
1272
1273                 if (report_path_error(ps_matched, &ps, NULL)) {
1274                         fprintf_ln(stderr, _("Did you forget to 'git add'?"));
1275                         ret = -1;
1276                         free(ps_matched);
1277                         goto done;
1278                 }
1279                 free(ps_matched);
1280         }
1281
1282         if (refresh_cache(REFRESH_QUIET)) {
1283                 ret = -1;
1284                 goto done;
1285         }
1286
1287         if (!check_changes(ps, include_untracked, &untracked_files)) {
1288                 if (!quiet)
1289                         printf_ln(_("No local changes to save"));
1290                 goto done;
1291         }
1292
1293         if (!reflog_exists(ref_stash) && do_clear_stash()) {
1294                 ret = -1;
1295                 if (!quiet)
1296                         fprintf_ln(stderr, _("Cannot initialize stash"));
1297                 goto done;
1298         }
1299
1300         if (stash_msg)
1301                 strbuf_addstr(&stash_msg_buf, stash_msg);
1302         if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode,
1303                             &info, &patch, quiet)) {
1304                 ret = -1;
1305                 goto done;
1306         }
1307
1308         if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
1309                 ret = -1;
1310                 if (!quiet)
1311                         fprintf_ln(stderr, _("Cannot save the current status"));
1312                 goto done;
1313         }
1314
1315         if (!quiet)
1316                 printf_ln(_("Saved working directory and index state %s"),
1317                           stash_msg_buf.buf);
1318
1319         if (!patch_mode) {
1320                 if (include_untracked && !ps.nr) {
1321                         struct child_process cp = CHILD_PROCESS_INIT;
1322
1323                         cp.git_cmd = 1;
1324                         argv_array_pushl(&cp.args, "clean", "--force",
1325                                          "--quiet", "-d", NULL);
1326                         if (include_untracked == INCLUDE_ALL_FILES)
1327                                 argv_array_push(&cp.args, "-x");
1328                         if (run_command(&cp)) {
1329                                 ret = -1;
1330                                 goto done;
1331                         }
1332                 }
1333                 discard_cache();
1334                 if (ps.nr) {
1335                         struct child_process cp_add = CHILD_PROCESS_INIT;
1336                         struct child_process cp_diff = CHILD_PROCESS_INIT;
1337                         struct child_process cp_apply = CHILD_PROCESS_INIT;
1338                         struct strbuf out = STRBUF_INIT;
1339
1340                         cp_add.git_cmd = 1;
1341                         argv_array_push(&cp_add.args, "add");
1342                         if (!include_untracked)
1343                                 argv_array_push(&cp_add.args, "-u");
1344                         if (include_untracked == INCLUDE_ALL_FILES)
1345                                 argv_array_push(&cp_add.args, "--force");
1346                         argv_array_push(&cp_add.args, "--");
1347                         add_pathspecs(&cp_add.args, ps);
1348                         if (run_command(&cp_add)) {
1349                                 ret = -1;
1350                                 goto done;
1351                         }
1352
1353                         cp_diff.git_cmd = 1;
1354                         argv_array_pushl(&cp_diff.args, "diff-index", "-p",
1355                                          "--cached", "--binary", "HEAD", "--",
1356                                          NULL);
1357                         add_pathspecs(&cp_diff.args, ps);
1358                         if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
1359                                 ret = -1;
1360                                 goto done;
1361                         }
1362
1363                         cp_apply.git_cmd = 1;
1364                         argv_array_pushl(&cp_apply.args, "apply", "--index",
1365                                          "-R", NULL);
1366                         if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
1367                                          NULL, 0)) {
1368                                 ret = -1;
1369                                 goto done;
1370                         }
1371                 } else {
1372                         struct child_process cp = CHILD_PROCESS_INIT;
1373                         cp.git_cmd = 1;
1374                         argv_array_pushl(&cp.args, "reset", "--hard", "-q",
1375                                          NULL);
1376                         if (run_command(&cp)) {
1377                                 ret = -1;
1378                                 goto done;
1379                         }
1380                 }
1381
1382                 if (keep_index == 1 && !is_null_oid(&info.i_tree)) {
1383                         struct child_process cp_ls = CHILD_PROCESS_INIT;
1384                         struct child_process cp_checkout = CHILD_PROCESS_INIT;
1385                         struct strbuf out = STRBUF_INIT;
1386
1387                         if (reset_tree(&info.i_tree, 0, 1)) {
1388                                 ret = -1;
1389                                 goto done;
1390                         }
1391
1392                         cp_ls.git_cmd = 1;
1393                         argv_array_pushl(&cp_ls.args, "ls-files", "-z",
1394                                          "--modified", "--", NULL);
1395
1396                         add_pathspecs(&cp_ls.args, ps);
1397                         if (pipe_command(&cp_ls, NULL, 0, &out, 0, NULL, 0)) {
1398                                 ret = -1;
1399                                 goto done;
1400                         }
1401
1402                         cp_checkout.git_cmd = 1;
1403                         argv_array_pushl(&cp_checkout.args, "checkout-index",
1404                                          "-z", "--force", "--stdin", NULL);
1405                         if (pipe_command(&cp_checkout, out.buf, out.len, NULL,
1406                                          0, NULL, 0)) {
1407                                 ret = -1;
1408                                 goto done;
1409                         }
1410                 }
1411                 goto done;
1412         } else {
1413                 struct child_process cp = CHILD_PROCESS_INIT;
1414
1415                 cp.git_cmd = 1;
1416                 argv_array_pushl(&cp.args, "apply", "-R", NULL);
1417
1418                 if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
1419                         if (!quiet)
1420                                 fprintf_ln(stderr, _("Cannot remove "
1421                                                      "worktree changes"));
1422                         ret = -1;
1423                         goto done;
1424                 }
1425
1426                 if (keep_index < 1) {
1427                         struct child_process cp = CHILD_PROCESS_INIT;
1428
1429                         cp.git_cmd = 1;
1430                         argv_array_pushl(&cp.args, "reset", "-q", "--", NULL);
1431                         add_pathspecs(&cp.args, ps);
1432                         if (run_command(&cp)) {
1433                                 ret = -1;
1434                                 goto done;
1435                         }
1436                 }
1437                 goto done;
1438         }
1439
1440 done:
1441         strbuf_release(&stash_msg_buf);
1442         return ret;
1443 }
1444
1445 static int push_stash(int argc, const char **argv, const char *prefix)
1446 {
1447         int keep_index = -1;
1448         int patch_mode = 0;
1449         int include_untracked = 0;
1450         int quiet = 0;
1451         const char *stash_msg = NULL;
1452         struct pathspec ps;
1453         struct option options[] = {
1454                 OPT_BOOL('k', "keep-index", &keep_index,
1455                          N_("keep index")),
1456                 OPT_BOOL('p', "patch", &patch_mode,
1457                          N_("stash in patch mode")),
1458                 OPT__QUIET(&quiet, N_("quiet mode")),
1459                 OPT_BOOL('u', "include-untracked", &include_untracked,
1460                          N_("include untracked files in stash")),
1461                 OPT_SET_INT('a', "all", &include_untracked,
1462                             N_("include ignore files"), 2),
1463                 OPT_STRING('m', "message", &stash_msg, N_("message"),
1464                            N_("stash message")),
1465                 OPT_END()
1466         };
1467
1468         if (argc)
1469                 argc = parse_options(argc, argv, prefix, options,
1470                                      git_stash_push_usage,
1471                                      0);
1472
1473         parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL, prefix, argv);
1474         return do_push_stash(ps, stash_msg, quiet, keep_index, patch_mode,
1475                              include_untracked);
1476 }
1477
1478 static int save_stash(int argc, const char **argv, const char *prefix)
1479 {
1480         int keep_index = -1;
1481         int patch_mode = 0;
1482         int include_untracked = 0;
1483         int quiet = 0;
1484         int ret = 0;
1485         const char *stash_msg = NULL;
1486         struct pathspec ps;
1487         struct strbuf stash_msg_buf = STRBUF_INIT;
1488         struct option options[] = {
1489                 OPT_BOOL('k', "keep-index", &keep_index,
1490                          N_("keep index")),
1491                 OPT_BOOL('p', "patch", &patch_mode,
1492                          N_("stash in patch mode")),
1493                 OPT__QUIET(&quiet, N_("quiet mode")),
1494                 OPT_BOOL('u', "include-untracked", &include_untracked,
1495                          N_("include untracked files in stash")),
1496                 OPT_SET_INT('a', "all", &include_untracked,
1497                             N_("include ignore files"), 2),
1498                 OPT_STRING('m', "message", &stash_msg, "message",
1499                            N_("stash message")),
1500                 OPT_END()
1501         };
1502
1503         argc = parse_options(argc, argv, prefix, options,
1504                              git_stash_save_usage,
1505                              PARSE_OPT_KEEP_DASHDASH);
1506
1507         if (argc)
1508                 stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
1509
1510         memset(&ps, 0, sizeof(ps));
1511         ret = do_push_stash(ps, stash_msg, quiet, keep_index,
1512                             patch_mode, include_untracked);
1513
1514         strbuf_release(&stash_msg_buf);
1515         return ret;
1516 }
1517
1518 static int use_builtin_stash(void)
1519 {
1520         struct child_process cp = CHILD_PROCESS_INIT;
1521         struct strbuf out = STRBUF_INIT;
1522         int ret, env = git_env_bool("GIT_TEST_STASH_USE_BUILTIN", -1);
1523
1524         if (env != -1)
1525                 return env;
1526
1527         argv_array_pushl(&cp.args,
1528                          "config", "--bool", "stash.usebuiltin", NULL);
1529         cp.git_cmd = 1;
1530         if (capture_command(&cp, &out, 6)) {
1531                 strbuf_release(&out);
1532                 return 1;
1533         }
1534
1535         strbuf_trim(&out);
1536         ret = !strcmp("true", out.buf);
1537         strbuf_release(&out);
1538         return ret;
1539 }
1540
1541 int cmd_stash(int argc, const char **argv, const char *prefix)
1542 {
1543         int i = -1;
1544         pid_t pid = getpid();
1545         const char *index_file;
1546         struct argv_array args = ARGV_ARRAY_INIT;
1547
1548         struct option options[] = {
1549                 OPT_END()
1550         };
1551
1552         if (!use_builtin_stash()) {
1553                 const char *path = mkpath("%s/git-legacy-stash",
1554                                           git_exec_path());
1555
1556                 if (sane_execvp(path, (char **)argv) < 0)
1557                         die_errno(_("could not exec %s"), path);
1558                 else
1559                         BUG("sane_execvp() returned???");
1560         }
1561
1562         prefix = setup_git_directory();
1563         trace_repo_setup(prefix);
1564         setup_work_tree();
1565
1566         git_config(git_diff_basic_config, NULL);
1567
1568         argc = parse_options(argc, argv, prefix, options, git_stash_usage,
1569                              PARSE_OPT_KEEP_UNKNOWN | PARSE_OPT_KEEP_DASHDASH);
1570
1571         index_file = get_index_file();
1572         strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
1573                     (uintmax_t)pid);
1574
1575         if (!argc)
1576                 return !!push_stash(0, NULL, prefix);
1577         else if (!strcmp(argv[0], "apply"))
1578                 return !!apply_stash(argc, argv, prefix);
1579         else if (!strcmp(argv[0], "clear"))
1580                 return !!clear_stash(argc, argv, prefix);
1581         else if (!strcmp(argv[0], "drop"))
1582                 return !!drop_stash(argc, argv, prefix);
1583         else if (!strcmp(argv[0], "pop"))
1584                 return !!pop_stash(argc, argv, prefix);
1585         else if (!strcmp(argv[0], "branch"))
1586                 return !!branch_stash(argc, argv, prefix);
1587         else if (!strcmp(argv[0], "list"))
1588                 return !!list_stash(argc, argv, prefix);
1589         else if (!strcmp(argv[0], "show"))
1590                 return !!show_stash(argc, argv, prefix);
1591         else if (!strcmp(argv[0], "store"))
1592                 return !!store_stash(argc, argv, prefix);
1593         else if (!strcmp(argv[0], "create"))
1594                 return !!create_stash(argc, argv, prefix);
1595         else if (!strcmp(argv[0], "push"))
1596                 return !!push_stash(argc, argv, prefix);
1597         else if (!strcmp(argv[0], "save"))
1598                 return !!save_stash(argc, argv, prefix);
1599         else if (*argv[0] != '-')
1600                 usage_msg_opt(xstrfmt(_("unknown subcommand: %s"), argv[0]),
1601                               git_stash_usage, options);
1602
1603         if (strcmp(argv[0], "-p")) {
1604                 while (++i < argc && strcmp(argv[i], "--")) {
1605                         /*
1606                          * `akpqu` is a string which contains all short options,
1607                          * except `-m` which is verified separately.
1608                          */
1609                         if ((strlen(argv[i]) == 2) && *argv[i] == '-' &&
1610                             strchr("akpqu", argv[i][1]))
1611                                 continue;
1612
1613                         if (!strcmp(argv[i], "--all") ||
1614                             !strcmp(argv[i], "--keep-index") ||
1615                             !strcmp(argv[i], "--no-keep-index") ||
1616                             !strcmp(argv[i], "--patch") ||
1617                             !strcmp(argv[i], "--quiet") ||
1618                             !strcmp(argv[i], "--include-untracked"))
1619                                 continue;
1620
1621                         /*
1622                          * `-m` and `--message=` are verified separately because
1623                          * they need to be immediately followed by a string
1624                          * (i.e.`-m"foobar"` or `--message="foobar"`).
1625                          */
1626                         if (starts_with(argv[i], "-m") ||
1627                             starts_with(argv[i], "--message="))
1628                                 continue;
1629
1630                         usage_with_options(git_stash_usage, options);
1631                 }
1632         }
1633
1634         argv_array_push(&args, "push");
1635         argv_array_pushv(&args, argv);
1636         return !!push_stash(args.argc, args.argv, prefix);
1637 }