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