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