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