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