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